<?php
/**
 * Created by PhpStorm.
 * User: zhuyujun
 * Date: 2017/10/24
 * Time: 15:21
 */

namespace App\Api\Service\Order\Controllers;


use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\CustomerAddress;
use App\Eloquent\Ygt\OrderListRelation;
use App\Eloquent\Ygt\OrderWage;
use App\Eloquent\Ygt\Plate;
use App\Eloquent\Ygt\ProcessOrdertype;
use Framework\BaseClass\Api\Controller;
use Illuminate\Http\Request;

use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\OrderPre;
use App\Eloquent\Ygt\UserMessage;
use App\Eloquent\Ygt\OrderBasic;
use App\Eloquent\Ygt\OrdertypeCategory;
//use App\Eloquent\Ygt\OrderType;
use App\Eloquent\Ygt\OrderDistributionPre;
use App\Eloquent\Ygt\OrderDistribution;
use App\Eloquent\Ygt\OrderProcessPre;
use App\Eloquent\Ygt\OrderProcess;
use App\Eloquent\Ygt\OrderMaterial;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\OrderProcessCourse;
use App\Eloquent\Ygt\OrderProcessCourseGradation;
use App\Eloquent\Ygt\OrderMaterialCourse;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\OrderReport;
use App\Eloquent\Ygt\OrderReportType;
use App\Eloquent\Ygt\OrderReportCell;
use App\Eloquent\Ygt\OrderFieldCompany;
//订单
use App\Eloquent\Ygt\CustomerOrderPre;
use App\Eloquent\Ygt\CustomerOrder;
use App\Eloquent\Ygt\CustomerOrderProcessPre;
use App\Eloquent\Ygt\CustomerOrderProcess;
use App\Eloquent\Ygt\CustomerOrderBilling;

use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Eloquent\Ygt\ProcessFieldRelationUnit;
use App\Eloquent\Ygt\ProcessField;
use  App\Eloquent\Ygt\Company;
use  App\Eloquent\Ygt\OrderPlate;
use  App\Eloquent\Ygt\CustomerInvoice;


use App\Eloquent\Province;
use App\Eloquent\City;
use App\Eloquent\Area;

use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\Permission;
use App\Engine\OrderType;
use App\Engine\Stock;
use App\Engine\Func;
use App\Engine\Product as ProductEngine;
use App\Engine\Permission as PermissionEngine;
use App\Engine\OrderEngine;
use App\Engine\Plate as PlateEngine;
use App\Engine\Customer as CustomerEngine;


use App\Eloquent\Oa\FlowCustomerOrder;//新加，客户订单流程
use App\Engine\Buyers;


use Framework\Services\ImageUpload\imageProcess;


class IndexController extends Controller
{
    /**
     * Description:工单类型选择(选择要生成的产品)
     * User: zhuyujun
     * @return array
     */
    public function getOrderTypeAll()
    {
        $categoryId = request('category_id');
        $companyId = request('company_id');
//        header('Content-type: application/json');
        //获取所有工单类型的表
        //工单类型全部
        $userId = Func::getHeaderValueByName('userid');
        if($userId){
            $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            if (!$companyId) {
                $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
            }
        }


//        $orderTypeAll = OrderType::all();
        $orderTypeObj = new OrderType();
        $where = ['company_id' => $companyId];
        if ($categoryId) {
            $where['category_id'] = $categoryId;
        }

//        $orderTypeAll = $orderTypeObj->getData($where);
        $orderTypeAll = $orderTypeObj->getOrderTypeList($where);

        //图片路径增加域名
        $orderTypeList = [];
        foreach ($orderTypeAll as $tmpRow) {
            $orderTypeList[] = [
                '$imageUrl' => ImgUpload::getImgUrlById($tmpRow->img_id),
                '$typeTitle' => $tmpRow->title,
                '$typeFunctionName' => $tmpRow->id
            ];
        }

        $returnOrderTypeList = [
            'pageID' => 9,
            'data' => [
                '$list' => $orderTypeList
            ]
        ];

        return $returnOrderTypeList;
    }

    public function getOrderTypeCategory()
    {
        $companyId = request('company_id');

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        if (!$companyId) {
            $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        }

        $where = [
            'company_id' => $companyId
        ];
        $ordertypeCategoryModel = new OrdertypeCategory();
        $list = $ordertypeCategoryModel->getData($where, 'id,cat_name');
        return $list;
    }

    /**
     * Description:提交工单类型
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderTypeSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        //校验参数
        $rules = [
            'order_type' => 'required',
        ];
        $message = [
            'order_type.required' => '未选择工单类型'
        ];
        $this->validateRequestParameters($input, $rules, true, $message);


        //创建预生成工单&返回预生成工单id
        $orderPreRow = OrderPre::firstOrNew(['id' => '']);

        //工单号调整为正式生成工单时创建
//        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $orderTitle = '';

        //用户id&企业id
        //$userId = request()->header('userid', 0);
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $insertRow = [
            'order_type' => $input['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
            'is_trash' => 1,//默认设置为该记录为可删除
        ];

        //获取客户订单信息
        $customerOrderId = isset($input['customer_order_id']) ? $input['customer_order_id'] : '';
        if ($customerOrderId) {//插入客户id和单位id
            $where = ['id' => $customerOrderId];
            $originalCustomerOrderRow = FlowCustomerOrder::where($where)->first()->toArray();
            $insertRow['customer_name'] = $originalCustomerOrderRow['customer_id'];
            $insertRow['field_name_23'] = $originalCustomerOrderRow['workplace'];
        }

        $orderPreRow->fill($insertRow);
        $orderPreRow->save();
        $orderId = $orderPreRow->id;

        return ['order_id' => $orderId];
    }

    /**
     * Description:工单创建-基础信息-选项参数获取
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderPreBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的工单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱工单id 测试数据

        $curOrderRow = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $distributionOrderId = $input['order_id'];
        if ($pre_order_id !== '') {
            //草稿箱
            $curOrderRow = OrderPre::where(['id' => $pre_order_id])->first()->toArray();
            $orderId = $pre_order_id;
            $distributionOrderId = $orderId;
        } else if ($input['copy_order_id']) {
            //再来一单
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到工单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $curOrderRow = Order::where(['id' => $input['copy_order_id']])->first()->toArray();
            //获取工单类型id
            $orderId = $input['order_id'];
            $distributionOrderId = $input['copy_order_id'];
        } else {
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到工单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $orderId = $input['order_id'];
        }

        //工单基础信息字段，目前格式固定
//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        //添加默认值
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {
                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

                        $customerAddressRow = CustomerAddress::where(['id' => $customerAddressId])->first();
                        $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];

                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }

                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);
                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }

            }
        }

        $orderPreRow = OrderPre::where('id', $orderId)->first()->toArray();
        $orderType = $orderPreRow['order_type'];

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        return [
            'process_title' => '基础信息',
            'order_base_field_list' => $orderBaseFieldList,
            'button_title' => '下一步',
            'create_order_title' => '创建工单（1/' . ($processNum + 1) . '）'
        ];
    }

    /**
     * Description:工单创建-基础信息-提交
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderPreBaseSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $process_field_list = $orderBaseFieldList;
            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($process_field_list as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }

//        //校验参数
//        $rules = [
//            'order_id' => 'required',
//        ];
//        $messages = [
//            'order_id.required' => '缺少工单id',
//        ];
//
//        $this->validateRequestParameters($input, $rules, true, $messages);

        //新加限制，产品数量必须填写数字
//        if (isset($input['product_num'])) {
//            $tmpArr = explode(',', $input['product_num']);
//            if (!is_numeric($tmpArr[0])) {
//                return [
//                    'code' => 1,
//                    'message' => '下单数量请填写数量'
//                ];
//            }
//        }
//        //交货日期不能晚于当天
//        if (isset($input['finished_date'])) {
//            if(date('Ymd') > date('Ymd',strtotime($input['finished_date']))){
//                return [
//                    'code' => 1,
//                    'message' => '交货日期不能晚于创建时间'
//                ];
//            }
//        }


        //数据入库
        //创建预生成工单&返回预生成工单id
        $orderId = $input['order_id'];
        $orderPreRow = OrderPre::firstOrNew(['id' => $orderId]);
        $orderType = $orderPreRow->order_type;

        //修改数据
        foreach ($orderBaseFieldList as $fieldRow) {
            ////调整为入库20180323
//            if (in_array($fieldRow['field_type'], array(8))) {//字段不入库
//                continue;
//            }
            if (isset($input[$fieldRow['field_name']])) {
                $tmpFieldName = $fieldRow['field_name'];
                $orderPreRow->$tmpFieldName = $input[$fieldRow['field_name']];
            }
        }


//        $orderPreRow->contract_number = $input['contract_number'];//'合同编号'
//        $orderPreRow->customer_name = $input['customer_name'];//'客户名称'
//        $orderPreRow->product_name = $input['product_name'];//'产品名称'
//        $orderPreRow->product_num = $input['product_num'];//'产品数量'
////        $orderPreRow->grammage = $input['grammage'];//'克数'
////        $orderPreRow->chip_specification_length = $input['chip_specification_length'];//'片料规格-长'
////        $orderPreRow->chip_specification_width = $input['chip_specification_width'];//'片料规格-宽'
////        $orderPreRow->finished_weight = $input['finished_weight'];//'成品重量'
//        $orderPreRow->finished_date = $input['finished_date'];//'交货日期'
////        $orderPreRow->weaving_type = $input['weaving_type'];//'织布类型'
////        $orderPreRow->plate_numbering = $input['plate_numbering'];//'印版编号'
////        $orderPreRow->plate_position = $input['plate_position'];//'印版位置'
////        $orderPreRow->plate_modification = $input['plate_modification'];//'印版修改'
////        $orderPreRow->public_plate = $input['public_plate'];//'公用印版'
//        $orderPreRow->is_priority = $input['is_priority'];//'是否优先'
////        $orderPreRow->enterprise_icon = isset($input['enterprise_icon']) ? $input['enterprise_icon'] : '';//企业图标(图片地址id)
//        $orderPreRow->production_case_diagram = isset($input['production_case_diagram']) ? $input['production_case_diagram'] : '';//生产实例图,图片地址id（多个用’,‘隔开， 例如 11,23,55）
        $orderPreRow->status = 4;//工单状态 1-待接单 2-生产中 3-已完成 4-待派发状态
        $orderPreRow->is_trash = 0;//标记为不自动删除
        $orderPreRow->save();
//        return ['message'=>'提交成功'];
        $orderPreRow->id;

        //返回该工单类型的第一个工序
        $orderTypeObj = new OrderType();
//        $firstProcessId = $orderTypeObj->getFirstOneProcessId($orderType);
        $firstProcessRow = $orderTypeObj->getFirstStep($orderType);
        $firstProcessId = $firstProcessRow['process_id'];
        $firstOrdertypeProcessId = $firstProcessRow['id'];

        return [
            'process_id' => $firstProcessId,
            'ordertype_process_id' => $firstOrdertypeProcessId,
        ];
    }

    //工单创建-配送消息提交
    public function orderPreDistributionSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //校验参数
        $rules = [
            'order_id' => 'required',
        ];
        $messages = [
            'order_id.required' => '缺少工单id',
        ];

        $this->validateRequestParameters($input, $rules, true, $messages);

        //数据入库
        //创建预生成工单&返回预生成工单id
        $orderDistributionPreRow = OrderDistributionPre::firstOrNew(['order_id' => $input['order_id']]);
        $insertRow = [
            'order_id' => $input['order_id'],//关联的工单id
            'consignee' => $input['consignee'],//'收货人'
            'phone' => $input['phone'],//'电话'
            'province_id' => $input['province_id'],//'省-id'
            'province_name' => $input['province_name'],//'省-名称'
            'city_id' => $input['city_id'],//'市-id'
            'city_name' => $input['city_name'],//'市-名称'
            'area_id' => $input['area_id'],//'区-id'
            'area_name' => $input['area_name'],//'区-名称'
            'address' => $input['address'],//'详细地址'
        ];

        $orderDistributionPreRow->fill($insertRow);
        $orderDistributionPreRow->save();
        $orderDistributionPreRow->id;

//        return ['message'=>'提交成功'];
        return $orderDistributionPreRow->id;

    }

    /**
     * Description:正式生成工单数据
     * User: zhuyujun
     * @param $orderPreId
     */
    public function orderCreate($orderPreId)
    {
        $orderId = '';
        //基础信息
        //取出预生成数据
        $orderPre = OrderPre::where('id', $orderPreId);
        $orderPreRow = $orderPre->first()->toArray();

        //获取登陆用户信息
        $userId = $orderPreRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //存入正式数据
        $order = Order::firstOrNew(['id' => '']);
        unset($orderPreRow['id']);//不使用预生成表的id
        unset($orderPreRow['is_trash']);//删除草稿箱表独有的字段
        $orderPreRow['order_pre_id'] = $orderPreId;//存入对应的草稿箱

        ////生成工单号
        //获取该工单是当天的第几单
        $dayStartTime = strtotime(date('Ymd'));
        $intradayOrderCount = Order::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

        $ordeTitleIndex = '';
        $intradayOrderCount++;
        if ($intradayOrderCount < 10) {
            $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
        } else {
            $ordeTitleIndex = $intradayOrderCount;
        }
        $orderPreRow['order_title'] = 'GD' . date('ymd') . $ordeTitleIndex;

        $order->fill($orderPreRow);
        $order->save();
        $orderId = $order->id;
        $foreignKey = intval($order->customer_order_id);
        //删除预生成数据
        //基础信息
        $orderPre->delete();

        //数据加入到工单列表关联表中
        $orderPreRow['id'] = $orderId;
        OrderEngine::importMainOrder($orderPreRow);

////改为选择客户地址
//        //配送信息
//        //取出预生成数据
//        $orderDistributionPre = OrderDistributionPre::where('order_id', $orderPreId);
//        $orderDistributionPreRow = $orderDistributionPre->first();
//        if ($orderDistributionPreRow) {
//            $orderDistributionPreRow = $orderDistributionPreRow->toArray();
//            //存入正式数据
//            $orderDistribution = OrderDistribution::firstOrNew(['id' => '']);
//            $orderDistributionPreRow['order_id'] = $orderId;
//            $orderDistribution->fill($orderDistributionPreRow);
//            $orderDistribution->save();
//            $orderDistribution->id;
//            //删除预生成数据
//            $orderDistributionPre->delete();
//        }

        //工序信息处理
        $orderProcessPreList = OrderProcessPre::where('order_id', $orderPreId)->get();

        //获取第一道步骤涉及的工序
        $processFirstList = OrderType::getFirstProcessBag($orderPreRow['order_type'])->toArray();

        $allMaterialList = [];//保存所有材料信息
        foreach ($orderProcessPreList as $orderProcessPreObj) {
            $orderProcessPreRow = $orderProcessPreObj->toArray();
            //存入正式数据
            $orderProcess = OrderProcess::firstOrNew(['id' => '']);
            $orderProcessPreRow['order_id'] = $orderId;
            $orderProcessPreRow['status'] = 1;//工单工序默认状态为，1-待接单 2-确认开工（未领取材料） 3-已领取材料 4-确认完工
            $orderProcess->fill($orderProcessPreRow);
            $orderProcess->save();

            ////添加材料
            //获取字段信息
            $processFieldList = Process::getFieldListByProcessId($orderProcessPreRow['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    $materialList = explode(',', $orderProcessPreRow[$processFieldRow['field_name']]);
                    foreach ($materialList as $materialsId) {
                        //过滤空格
                        if (!trim($materialsId)) {
                            continue;
                        }

                        if(!in_array($materialsId,$allMaterialList)){
                            $allMaterialList[] = $materialsId;
                        }

                        $orderMaterialObj = OrderMaterial::firstOrNew(['order_id' => $orderProcessPreRow['order_id'], 'process_type' => $orderProcessPreRow['process_type'], 'material_id' => $materialsId]);
                        $orderMaterialRow = [
                            'order_id' => $orderProcessPreRow['order_id'],
                            'process_type' => $orderProcessPreRow['process_type'],
                            'material_id' => $materialsId,
                            'company_id' => $companyId,
                        ];
                        $orderMaterialObj->fill($orderMaterialRow);
                        $orderMaterialObj->save();
                    }
                }

            }

            //删除预生成数据
            $orderProcessPreObj->delete();
        }

        $productIds = OrderMaterial::where('order_id', $orderId)->get()->pluck('material_id');

        $where = [];
        $where[] = ['whereRaw', 'number <= warning_number'];
        $where['id'] = ['in', $productIds];
        $productModel = new Product();
        $count = $productModel->getCount($where);

        if ($count >= 1) {
            $products = $productModel->getData($where)->pluck('product_name')->toArray();

            $products = implode('、', $products);

            //给采购发送消息
            $privilegeIds = Privilege::getPrivilegeIds($companyId, 8);


            foreach ($privilegeIds as $val) {
                $meesageContent = '工单号：' . $order['order_title'] . " 需采购" . $products . "等材料";
                $data = [
                    'company_id' => $companyId, 'privilege_id' => $val,
                    'form_user_id' => $userId, 'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 10, 'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'], 'content' => $meesageContent
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }

        //增加订单类型使用次数
        $orderTypeId = $orderPreRow['order_type'];
        OrderType::incrementUseNum($orderTypeId);

        //如果是由订单转工单的，将最新的工单信息补充到订单信息中
        $customerOrderId = $orderPreRow['customer_order_id'];
        if ($customerOrderId) {
            //补充覆盖订单基础信息
            $curOrderInfo = Order::where(['id' => $orderId])->first()->toArray();
            //过滤不需要覆盖的字段
            unset($curOrderInfo['id']);
            unset($curOrderInfo['order_pre_id']);
            unset($curOrderInfo['created_at']);
            unset($curOrderInfo['updated_at']);
            unset($curOrderInfo['deleted_at']);
            unset($curOrderInfo['order_title']);
            unset($curOrderInfo['uid']);
            unset($curOrderInfo['customer_order_id']);

            $customerOrderObj = CustomerOrder::where(['id' => $customerOrderId])->first();
            $customerOrderObj->fill($curOrderInfo);
            $customerOrderObj->save();

            //补充覆盖订单工序信息
            $curOrderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($curOrderProcessList as $curOrderProcessRow) {
                $orderTypeProcessId = $curOrderProcessRow['ordertype_process_id'];

                //过滤不需要覆盖的字段
                unset($curOrderProcessRow['id']);
                unset($curOrderProcessRow['order_id']);
                unset($curOrderProcessRow['uid']);
                unset($curOrderProcessRow['estimated_time_day']);
                unset($curOrderProcessRow['estimated_time_hour']);
                unset($curOrderProcessRow['estimated_time_minute']);
                unset($curOrderProcessRow['start_time']);

                $tmpCustomerProcessOrderObj = CustomerOrderProcess::where(['order_id' => $customerOrderId, 'ordertype_process_id' => $orderTypeProcessId])->first();
                $tmpCustomerProcessOrderObj->fill($curOrderProcessRow);
                $tmpCustomerProcessOrderObj->save();

            }

        }


        ////添加版和工单的关系
        //如果版在基础信息中添加
//        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
//        $orderInfo = Order::where(['id' => $orderId])->first();
//        foreach ($orderBaseFieldList as $orderBaseFieldRow) {
//            if ($orderBaseFieldRow['field_type'] == 17) {
//                $tmpFiledName = $orderBaseFieldRow['field_name'];
//                if ($orderInfo->$tmpFiledName) {
//                    //添加关联关系
//                    $orderPlateObj = OrderPlate::firstOrNew(['id' => '']);
//                    $insertRow = [];
//                    $insertRow['order_id'] = $orderId;
//                    $insertRow['plate_id'] = $orderInfo->$tmpFiledName;
//                    $insertRow['company_id'] = $companyId;
//                    $orderPlateObj->fill($insertRow);
//                    $orderPlateObj->save();
//                }
//            }
//        }

        ////关联添加调整到工序完成时
//        //如果版在工序信息中添加
//        $where = ['order_id' => $orderId];
//        $orderProcessList = OrderProcess::where($where)->get();
//        foreach ($orderProcessList as $orderProcessObj) {
//            //获取字段信息
//            $processFieldList = Process::getFieldListByProcessId($orderProcessObj->process_type);
//            foreach ($processFieldList as $processFieldRow) {
//                $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
//                if ($tmpFiledType == 17) {//添加关联关系
//                    $tmpFiledName = $processFieldRow['field_name'];
//                    if ($orderProcessObj->$tmpFiledName) {
//                        //添加关联关系
//                        $orderPlateObj = OrderPlate::firstOrNew(['id' => '']);
//                        $insertRow = [];
//                        $insertRow['order_id'] = $orderId;
//                        $insertRow['order_process_id'] = $orderProcessObj->id;
//                        $insertRow['plate_id'] = $orderProcessObj->$tmpFiledName;
//                        $insertRow['company_id'] = $companyId;
//
//                        //获取需要存入表的关联字段
//                        $orderPlateField = OrderEngine::getOrderPlateField();
//                        $content = '';
//                        foreach ($orderPlateField as $item => $filedRow) {
//                            $fieldName = $filedRow['field'];
//                            if (!isset($orderProcessObj->$fieldName)) {
//                                $filedValue = '';
//                            } else {
//                                $filedValue = $orderProcessObj->$fieldName;
//                            }
//                            $content[$item] = $filedValue;
//                        }
//
//                        $insertRow['content'] = serialize($content);
//                        $orderPlateObj->fill($insertRow);
//                        $orderPlateObj->save();
//                    }
//                }
//            }
//        }

        ////创建工单时，发送消息给采购员，提示采购员所需的材料及库存
        //获取下单人名字
        if(!empty($allMaterialList)){

            $orderCreaterName = DepartmentUser::getCurrentInfo($userId);
            if($orderCreaterName){
                $orderCreaterName = $orderCreaterName->truename;
            }else{
                $orderCreaterName = '';
            }


            $messageContent = "{$orderCreaterName}新创建了工单rnrn";
            $messageContent .= "工单需使用以下材料：rnrn";

            //获取所有材料信息
            foreach($allMaterialList as $tmpMaterialId){
                //获取材料信息
                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                $tmpMaterialName = $tmpMaterialRow['product_name'];
                $tmpMaterialNum = $tmpMaterialRow['number'];
                $tmpMaterialUnit = $tmpMaterialRow['unit'];

                $messageContent .= "{$tmpMaterialName} {$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
            }


            //发送消息给采购员
            $purchasingAgentPrivilegeList         = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 10 );

            foreach ($purchasingAgentPrivilegeList as $purchasingAgentPrivilegeId){
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $purchasingAgentPrivilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 20,//发送给采购员的消息
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }

        return $orderId;
    }


    /**
     * Description:获取省市区联动数据
     * User: zhuyujun
     * @param Request $request
     * @return mixed
     */
    public function getCityList(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        $type = isset($input['type']) ? $input['type'] : '';
        $provinceId = isset($input['provinceId']) ? $input['provinceId'] : '';
        $cityId = isset($input['cityId']) ? $input['cityId'] : '';

        if ($type == 1) {//获取省列表
            $provinceList = Province::all();
            foreach ($provinceList as $row) {
                $row->cid = $row->provinceID;
                $row->cat_name = $row->province;
            }
            $provinceList = $provinceList->toArray();
            return $provinceList;
        } elseif ($type == 2) {//获取市列表
            $cityList = City::where('fatherID', $provinceId)->get();
            foreach ($cityList as $row) {
                $row->cid = $row->cityID;
                $row->cat_name = $row->city;
                $row->aid = $row->cityID;
                $row->subject = $row->city;
            }
            $cityList = $cityList->toArray();
            return $cityList;
        } elseif ($type == 3) {//获取区列表
            $areaList = Area::where('fatherID', $cityId)->get();
            foreach ($areaList as $row) {
                $row->cid = $row->areaID;
                $row->cat_name = $row->area;
                $row->aid = $row->areaID;
                $row->subject = $row->area;
            }
            $areaList = $areaList->toArray();
            return $areaList;
        } elseif ($type == 4) {//获取省市区列表，ios环境使用
            $provinceList = Province::all()->toArray();
            $cityList = City::all()->toArray();
            $areaList = Area::all()->toArray();
            $zone = [];
            foreach ($provinceList as $key => $province) {
                $city_arr = [];
                foreach ($cityList as $k => $city) {
                    if ($city['fatherID'] == $province['provinceID']) {
                        foreach ($areaList as $kk => $area) {
                            if ($area['fatherID'] == $city['cityID']) {
                                $city['arealist'][] = $area;
                            }
                        }
                        $city_arr[] = $city;
                    }
                }
                $province['citylist'] = $city_arr;
                $zone[] = $province;

            }
            return $zone;
        }
    }

    private function distributeData($orderList)
    {

        $returnOrderList = [];
        $dataList = [];
        foreach ($orderList as $orderRow) {
            $type = $orderRow['type'];//工单类型 1-主工单 2-工序管理员工单 3-查看权限用户的工序工单 4-员工工单
            $status = $orderRow['status'];//不同类型工单，状态有所不同
            $orderRowContent = unserialize($orderRow['content']);

            //获取生产实例图
//            $productionCaseDiagramIds = isset($orderRowContent['production_case_diagram']) ? $orderRowContent['production_case_diagram'] : '';
//            if ($productionCaseDiagramIds) {
//                $tmpArr = explode(',', $productionCaseDiagramIds);
//                $productionCaseDiagramId = reset($tmpArr);
//                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
//                if (!$productionCaseDiagram) {//未获取到id对应的图片
//                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
//                }
//
//            } else {
//                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
//            }
            $productionCaseDiagram = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['production_case_diagram'],9);

//            if (isset($orderRowContent['product_num'])) {
//                $tmpArr = explode(',', $orderRowContent['product_num']);
//                $orderRowContent['product_num'] = '';
//                foreach ($tmpArr as $tmpValue) {
//                    $orderRowContent['product_num'] .= $tmpValue;
//                }
//            }

            $orderRowContent['product_num'] = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['product_num'],5);

//            //成品规格数据处理
//            if (isset($orderRowContent['finished_specification'])) {
//                $tmpArr = explode(',', $orderRowContent['finished_specification']);
//                if (count($tmpArr) == 2) {
//                    $orderRowContent['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
//                }
//
//                if (count($tmpArr) == 3) {
//                    $orderRowContent['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
//                }
//
//                //如果数据都为空，显示为空
//                $hasData = false;
//                foreach ($tmpArr as $tmpValue) {
//                    if ($tmpValue) {
//                        $hasData = true;
//                    }
//                }
//
//                if (!$hasData) {
//                    $orderRowContent['finished_specification'] = '';
//                }
//            }

            $orderRowContent['finished_specification'] = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['finished_specification'],16);



//            //单位名称显示处理
//            if (isset($orderRowContent['field_name_23'])) {
//                $baseId = $orderRowContent['field_name_23'];
//                $showTitle = Buyers::getNameById($orderRowContent['field_name_23']);
//                if (!$showTitle) {
//                    $showTitle = $orderRowContent['field_name_23'];
//                }
//                $orderRowContent['field_name_23'] = $showTitle;
//            }

            $orderRowContent['field_name_23'] = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['field_name_23'],19);


            //订单创建时间（派发时间）
            $orderCreateTime = $orderRow['order_create_time'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($orderRowContent['order_type'], 'title');


            //工单列表不同类型相同字段，统一管理
            $commonArr = [
                '$customer_title' => '单位名称',//工单列表展示字段
                '$product_title' => '品名',//工单列表展示字段
                '$order_title' => '单号',//工单列表展示字段
                '$customer_name' => isset($orderRowContent['field_name_23']) ? $orderRowContent['field_name_23'] : '',//新加字段客户
                '$product_name' => isset($orderRowContent['product_name']) ? $orderRowContent['product_name'] : '',//新加字段品名
                '$order_title_value' => $orderRowContent['order_title'],//新加字段单号
                '$firstPropertyName' => '成品规格',
                '$secondPropertyName' => '数量',
                '$thirdPropertyName' => '交货日期',
                '$thirdPropertyValue' => $orderRowContent['finished_date'],
                '$secondPropertyValue' => $orderRowContent['product_num'],
                '$firstPropertyValue' => isset($orderRowContent['finished_specification']) ? $orderRowContent['finished_specification'] : '',
                '$productionCaseDiagram' => $productionCaseDiagram,
                '$productOrderTimeValue' => $orderCreateTime,
                '$orderTypeTitle' => $orderTypeTitle,
                '$orderNumberValue' => $orderTypeTitle,
                '$orderTimeValue' => $orderRowContent['finished_date'],
                '$relate_id' => $orderRow['relate_id'],
            ];

            if ($type == 1) {//1-主工单
                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 5,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待接单',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);

                } elseif ($status == 101) {//待开工
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 2) {//生产中
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 3) {//已完工
                    $tmpArr = [
                        'idName' => 6,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 4) {//待派发
                    continue;//未派发工单另外处理
                }
            } elseif ($type == 2) {//2-工序管理员工单
                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 1,
                        '$itemFunctionName' => 'productdirectorWaitCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'productdirectorOrderSure' . $orderRow['relate_id'],
                        '$orderSureBgImage' => 'orderCellStatusButton.png',
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待接单',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 2) {//生产中-未分配工单
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorWaitCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待分配',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 101) {//待开工
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorproductIngCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 3) {//生产中-已分配工单
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorproductIngCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',//生产中
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 4) {//已完工
                    $tmpArr = [
                        'idName' => 4,
                        '$itemFunctionName' => 'productdirectorDoneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',//已完成
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                }
            } elseif ($type == 3) {//3-查看权限用户的工序工单
                $orderStatusArr = [
                    '1' => '待接单',
                    '2' => '待分派',
                    '3' => '生产中',
                    '4' => '已完成',
                    '101' => '待开工',
                ];
                $orderStatusColorArr = [
                    '1' => 'FFB401',
                    '2' => 'FFB401',
                    '3' => 'FE7E57',
                    '4' => '04C9B3',
                    '101' => 'FFB401',
                ];

                if (!isset($orderStatusArr[$status])) {//异常处理
                    $orderStatusArr[$status] = '异常状态';
                    $orderStatusColorArr[$status] = 'FFB401';
                }

                $tmpArr = [
                    'idName' => 4,
                    '$itemFunctionName' => 'productdirectorDoneCellFunction' . $orderRow['relate_id'],
                    '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                    '$statusCode' => $status,//新增订单状态值
                    '$orderStatus' => $orderStatusArr[$status],
                    '$statusColor' => $orderStatusColorArr[$status],//待接单,待分派,待开工
                ];
                $dataList[] = array_merge($commonArr, $tmpArr);;
            } elseif ($type == 4) {//4-员工工单

                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 1,
                        '$itemFunctionName' => 'waitCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$orderSureBgImage' => 'draftsOrderCellStatusButton.png',
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 2) {//生产中-未领取材料
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productIngNoneGetFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待领料',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 3) {//生产中-已领取材料
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productIngNoneDoneFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',//生产中
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 4) {//已完工
                    $tmpArr = [
                        'idName' => 4,
                        '$itemFunctionName' => 'doneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',//已完成
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                }
            }
        }

        $returnOrderList['pageID'] = 0;
        $returnOrderList['data']['$tableviewSource'] = $dataList;

        return $returnOrderList;
    }

    /**
     * @return array
     * 客户订单列表
     */
    public function getCustomerOrderList()
    {

        $customerId = request('customer_id');
        $isAll = request('is_all');
        $params = [
            'customer_id' => $customerId
        ];

//        $rules = [
//            'customer_id' => 'required|integer',
//        ];
//        $this->validateRequestParameters($params, $rules);

        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';


        //获取订单信息
        if (!$isAll) {
            $where['customer_name'] = $customerId;
        }

        $where['company_id'] = $companyId;

        $customerOrderList = CustomerOrder::where($where)->orderby('updated_at', 'desc')->get();


        $tmpOrderList = [];
        foreach ($customerOrderList as $tmpCustomerOrderRow) {
            if (isset($tmpCustomerOrderRow['product_num'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['product_num']);
                $tmpCustomerOrderRow['product_num'] = '';
                foreach ($tmpArr as $tmpValue) {
                    $tmpCustomerOrderRow['product_num'] .= $tmpValue;
                }
            }

            //成品规格数据处理
            if (isset($tmpCustomerOrderRow['finished_specification'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['finished_specification']);
                if (count($tmpArr) == 2) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
                }

                if (count($tmpArr) == 3) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                }

                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($tmpArr as $tmpValue) {
                    if ($tmpValue) {
                        $hasData = true;
                    }
                }

                if (!$hasData) {
                    $tmpCustomerOrderRow['finished_specification'] = '';
                }
            }

            //单位名称显示处理
            if (isset($tmpCustomerOrderRow['field_name_23'])) {
                $baseId = $tmpCustomerOrderRow['field_name_23'];
                $showTitle = Buyers::getNameById($tmpCustomerOrderRow['field_name_23']);
                if (!$showTitle) {
                    $showTitle = $tmpCustomerOrderRow['field_name_23'];
                }
                $tmpCustomerOrderRow['field_name_23'] = $showTitle;
            }

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $tmpArr = $tmpCustomerOrderRow->toArray();
            $orderCreateTime = $tmpArr['created_at'];

            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');

            $customerOrderStatusList = config('order.customer_order_status_list');
            $tmpOrderList[] = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($tmpCustomerOrderRow['product_name']) ? $tmpCustomerOrderRow['product_name'] : '',//新加字段品名
                'order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                'secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpCustomerOrderRow['id'],
                'orderStatus' => isset($customerOrderStatusList[$tmpCustomerOrderRow['status']]) ? $customerOrderStatusList[$tmpCustomerOrderRow['status']] :'',
                'statusColor' => 'FFB401',
            ];
        }

        $orderList = $tmpOrderList;

        $re['pageID'] = 0;
        $re['data']['tableviewSource'] = $orderList;

        return $re;
    }

    /**
     * @return array
     * 版工单列表
     */
    public function getPlateOrderList()
    {

        $plateId = request('plate_id');
        $params = [
            'plate_id' => $plateId
        ];

        $rules = [
            'plate_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $where = [['company_id', '=', $companyId], ['plate_id', '=', $plateId]];
        $orderPlateList = OrderPlate::where($where)->orderBy('id','desc')->get();
        $allCount = $orderPlateList->count();
        $tmpArr = [];

        foreach ($orderPlateList as $orderPlateRow) {
            //获取工单详情
            $tmpOrderId = $orderPlateRow['order_id'];
            $tmpOrderInfo = Order::where(['id' => $tmpOrderId])->first()->toArray();

            //产品数量处理
            $productNum = '';
            if ($tmpOrderInfo['product_num']) {
                $tmpProductNumArr = explode(',', $tmpOrderInfo['product_num']);
                if (isset($tmpProductNumArr[0])) {
                    $productNum = $tmpProductNumArr[0];
                }
            }

            $tmpArr[] = [
                'order_plate_id' => $orderPlateRow['id'],//工单id
                'order_id' => $tmpOrderInfo['id'],//工单id
                'order_title' => $tmpOrderInfo['order_title'],//工单号
//                'product_num' => $productNum,//产品数量
                'product_num' => isset($orderPlateRow['number']) ? $orderPlateRow['number'] : '',//产品数量
                'product_name' => $tmpOrderInfo['product_name'],//产品名称
                'create_date' => date('Y-m-d', $tmpOrderInfo['created_at']),//创建时间
            ];
        }
        $orderPlateList = $tmpArr;

        return [
            'allCount' => $allCount,
            'orderPlateList' => $orderPlateList,
        ];

    }

    /**
     * Description:获取工单列表
     * User: zhuyujun
     */
    public function getOrderList()
    {

        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $isDistribute = request('is_distribute');//是否派发 1-已派发 0-未派发
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        $isSupremeAuthority = Privilege::getAppnodeId($userInfo['privilege_id'], 9);//是否为厂长（最高权限）

        //工单筛选
        $orderStauts = request('order_status');//筛选的工单状态，1-待开工 2-进行中 3-已完成
        $orderTitle = request('order_title');//筛选的工单号


        $customerId = request('customer_id');//筛选的工单号
        if ($customerId) {
            $orderList = OrderListRelation::where(['type' => 1, 'customer_id' => $customerId])->orderBy('order_create_time', 'desc')->get()->toArray();
            return $this->distributeData($orderList);
        }


        if ($isDistribute) {//已派发
            ////新方法实现工单列表
            //处理工单状态搜索
            if (!$orderStauts) {
                if($isSupremeAuthority){
                    $where = [['company_id', '=', $companyId]];
                }else{
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId]];
                }


                //下单人不展示工序订单
                if ($isManager || $isSupremeAuthority) {
                    $where[] = ['type', '!=', 2];
                }

                if ($orderTitle) {
                    $where[] = ['content', 'like', '%' . $orderTitle . '%'];
                }
                $orderList = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();
            } else {
                if ($orderStauts == 1) {//待接单
                    //主订单
                    if($isSupremeAuthority){
                        $where = [['company_id', '=', $companyId], ['status', '=', 1], ['type', '=', 1]];
                    }else{
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['status', '=', 1], ['type', '=', 1]];
                    }


                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $where[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList1 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //工序订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $whereTypeIn = [2, 3];
                    $whereStatusIn = [1, 2, 101];
                    $orderList2 = OrderListRelation::where($where)->whereIn('type', $whereTypeIn)->whereIn('status', $whereStatusIn)->orderBy('order_create_time', 'desc')->get()->toArray();


                    //员工订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 4]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $whereStatusIn = [1, 2, 101];
                    $orderList3 = OrderListRelation::where($where)->whereIn('status', $whereStatusIn)->orderBy('order_create_time', 'desc')->get()->toArray();

                    $orderList = array_merge($orderList1, $orderList2, $orderList3);
                } elseif ($orderStauts == 2) {//进行中
                    //主订单
                    if($isSupremeAuthority){
                        $where = [['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 2]];
                    }else{
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 2]];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList1 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //工序订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['type', '!=', 4], ['status', '=', 3]];

                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $where[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList2 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //员工订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 4], ['status', '=', 3]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList3 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();
                    $orderList = array_merge($orderList1, $orderList2, $orderList3);

                } elseif ($orderStauts == 3) {//已完成
                    if($isSupremeAuthority){
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 3]];
                        $orWhere = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['status', '=', 4]];
                    }else{
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 3]];
                        $orWhere = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['status', '=', 4]];
                    }

                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $orWhere[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                        $orWhere[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList = OrderListRelation::where($where)->orWhere($orWhere)->orderBy('order_create_time', 'desc')->get()->toArray();
                }
            }

            return $this->distributeData($orderList);
        } else {//未派发工单
            if($isSupremeAuthority){
                $orderList = Order::where('status', 4)->orderBy('id', 'desc')->get()->toArray();
            }else{
                $orderList = Order::where('status', 4)->where(['uid' => $userId])->orderBy('id', 'desc')->get()->toArray();
            }


            foreach ($orderList as $k => $v) {
                $orderList[$k]['created_at'] = date('Y年m月d日', $v['created_at']);
                $orderList[$k]['updated_at'] = date('Y年m月d日', $v['updated_at']);
            }

            return $orderList;
        }

    }

    //未派发列表(新)
    public function getNoAssignOrderList(){
        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $isDistribute = request('is_distribute');//是否派发 1-已派发 0-未派发
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        $isSupremeAuthority = Privilege::getAppnodeId($userInfo['privilege_id'], 9);//是否为厂长（最高权限）

        if($isSupremeAuthority){
            $orderList = Order::where('status', 4)->where(['company_id' => $companyId])->orderBy('id', 'desc')->get()->toArray();
        }else{
            $orderList = Order::where('status', 4)->where(['company_id' => $companyId,'uid' => $userId])->orderBy('id', 'desc')->get()->toArray();
        }


        $newOrderList = [];
        foreach ($orderList as $k => $tmpOrderRow) {
            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpOrderRow['production_case_diagram']) ? $tmpOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            if (isset($tmpOrderRow['product_num'])) {
                $tmpArr = explode(',', $tmpOrderRow['product_num']);
                $tmpOrderRow['product_num'] = '';
                foreach ($tmpArr as $tmpValue) {
                    $tmpOrderRow['product_num'] .= $tmpValue;
                }
            }

            //成品规格数据处理
            if (isset($tmpOrderRow['finished_specification'])) {
                $tmpArr = explode(',', $tmpOrderRow['finished_specification']);
                if (count($tmpArr) == 2) {
                    $tmpOrderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
                }

                if (count($tmpArr) == 3) {
                    $tmpOrderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                }

                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($tmpArr as $tmpValue) {
                    if ($tmpValue) {
                        $hasData = true;
                    }
                }

                if (!$hasData) {
                    $tmpOrderRow['finished_specification'] = '';
                }
            }

            //单位名称显示处理
            if (isset($tmpOrderRow['field_name_23'])) {
                $baseId = $tmpOrderRow['field_name_23'];
                $showTitle = Buyers::getNameById($tmpOrderRow['field_name_23']);
                if (!$showTitle) {
                    $showTitle = $tmpOrderRow['field_name_23'];
                }
                $tmpOrderRow['field_name_23'] = $showTitle;
            }


            //订单创建时间（派发时间）
            $orderCreateTime = $tmpOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpOrderRow['order_type'], 'title');

            $tmpDataRow = [
                'customer_title' => '单位名称',//工单列表展示字段
                'product_title' => '品名',//工单列表展示字段
                'order_title' => '单号',//工单列表展示字段
                'customer_name' => isset($tmpOrderRow['field_name_23']) ? $tmpOrderRow['field_name_23'] : '',//新加字段客户
                'product_name' => isset($tmpOrderRow['product_name']) ? $tmpOrderRow['product_name'] : '',//新加字段品名
                'order_title_value' => $tmpOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpOrderRow['finished_date'],
                'secondPropertyValue' => $tmpOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpOrderRow['finished_specification']) ? $tmpOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'orderNumberValue' => $orderTypeTitle,
                'orderTimeValue' => $tmpOrderRow['finished_date'],
                'relate_id' => $tmpOrderRow['id'],
                'orderStatus' => '待派发',
                'order_type' => $tmpOrderRow['order_type'],
            ];

            $newOrderList[]=$tmpDataRow;
        }

        return $newOrderList;
    }


    //获取工单详情
    public function getOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工工单id
        $inputType = isset($input['type']) ? $input['type'] : 0;
        $inputUserId = isset($input['user_id']) ? $input['user_id'] : 0;


        $userId = Func::getHeaderValueByName('userid');

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $input['order_process_id'] = $orderProcessCourseRow['order_process_id'];
            $userId = $orderProcessCourseRow['uid'];
        }

//        if($inputType==1 && $inputUserId>0)
//        {
//            $userId = $inputUserId;
//        }
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        //获取用户的权限
        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();

        $apeList = [];

        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);


            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];

        }


        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }


            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            //员工订单详情-工单的需完成数量改为员工被派发的数量
            if ($input['order_process_course_id']) {//用户为员工
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }

            $apeList[] = [
                '$leftLabelValue' => $processFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];
        }


        //追加需完成数量
        if ($orderProcessInfo['completed_number']) {
            $apeList[] = [
                '$leftLabelValue' => '需完成数量',
                '$rightLabelValue' => $orderProcessInfo['completed_number'],
            ];
        }


        //添加计件工资
        $orderProcessId = $orderProcessInfo['id'];
        if(isset($orderProcessId,$privilegeId,$orderProcessCourseId)){
            $pieceWage= \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId,$privilegeId,$orderProcessCourseId);
            $apeList[] = [
                '$leftLabelValue' => '计件工资',
                '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
            ];
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preProcessList) {
            $preProcessList = $preProcessList->toArray();
        } else {
            $preProcessList = [];
        }


        //获取工序数量是否需要叠加&工序名称
        $processId = $orderProcessInfo['process_type'];
        $where = ['id' => $processId];
        $process = Process::getInfo($where)->toArray();

        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $preOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $preProcess = Process::getOneValueById($preOrderProcessInfo['process_type'], 'title');
                $processIsSum = Process::getOneValueById($preOrderProcessInfo['process_type'], 'is_sum');
                $lastOrderProcessId = $preOrderProcessInfo['id'];
                if ($preOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $preOrderProcessInfo['id']])->get();
                    $finishNum = 0;
                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = '预计完成时间:' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                        }


                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }


                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }


                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                    }


                    if ($preOrderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }
                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
        }


        //返回数据权限
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        if (in_array(3, $userRights) || $isManager) {//有分配权限或者是管理员权限
            if ($orderProcessInfo['status'] == 1) {
                $sureButtonFunctionName = 'orderSureAction';
                $buttonTitleValue = '确认接单';
            } elseif ($orderProcessInfo['status'] == 2) {
                $sureButtonFunctionName = 'allotOrderAction';
                $buttonTitleValue = '派发工单';
            }

            $returnOrderInfo = [];
            $returnOrderInfo['pageID'] = 3;
            $returnOrderInfo['completed_number'] = $orderProcessInfo['completed_number'];
            $returnOrderInfo['data'] = [
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$productTimeValue' => '交货日期:' . $orderInfo['finished_date'],
                '$futureTimeValue' => $preProcessEstimatedTimeStr,
                '$prevDepartmentValue' => $preProcess,
                '$last_order_process_finish_num' => $finishNum,//上一部门完成数量
                '$lastOrderProcessId' => $lastOrderProcessId,
                '$titleLabelValue' => $processTitle,
                '$commentValue' => $orderProcessInfo['remark'],
                '$buttonTitleValue' => $buttonTitleValue,
                '$sureButtonFunctionName' => $sureButtonFunctionName . $orderProcessInfo['id'],
                '$imageClick' => 'imageClickAction' . $orderInfo['id'],
                '$productImagrUlr' => $exampleImg,
                '$list' => $apeList,
            ];
        } else {

            //判断员工能否开工
            $orderProcessId = $orderProcessInfo['id'];
            //获取前一步骤所有工艺
            $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
            if ($preOrderProcessList) {
                $preOrderProcessList = $preOrderProcessList->toArray();
            } else {
                $preOrderProcessList = [];
            }


            $returnOrderInfo = [];
            $returnOrderInfo['pageID'] = 3;
            $returnOrderInfo['data'] = [
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$productTimeValue' => '交货日期:' . $orderInfo['finished_date'],
                '$futureTimeValue' => $preProcessEstimatedTimeStr,
                '$prevDepartmentValue' => $preProcess,
                '$last_order_process_finish_num' => $finishNum,//上一部门完成数量
                '$lastOrderProcessId' => $lastOrderProcessId,
                '$titleLabelValue' => $processTitle,
                '$list' => $apeList,
                '$commentValue' => $orderProcessInfo['remark'],
                '$buttonTitleValue' => '确认开工',
                '$sureButtonFunctionName' => 'sureGoAction' . $orderProcessCourseId,
                '$imageClick' => 'imageClickAction' . $orderInfo['id'],
                '$productImagrUlr' => $exampleImg
            ];

        }
//        if($inputType==1)
//        {
//            $returnOrderInfo['data']['$buttonTitleValue']='车间版开工';
//        }
        return $returnOrderInfo;
    }

    //确认开工
    public function confirmStart(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $input['estimated_time_hour'] = isset($input['estimated_time_hour']) ? $input['estimated_time_hour'] : '';//预估时间
        $input['estimated_time_minute'] = isset($input['estimated_time_minute']) ? $input['estimated_time_minute'] : '';//预估时间

        //处理时间，通过预计完成时间，推算出耗时多少小时多少分
        $curTime = time();
        if ($input['estimated_time_hour']) {
            //计算到指定时间需要的秒数
            $needTime = strtotime($input['estimated_time_hour']) - time();
            $input['estimated_time_minute'] = $needTime / 60;
            $input['estimated_time_hour'] = 0;
        }

        $userId = Func::getHeaderValueByName('userid');

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
            $userId =  $orderProcessCourseRow['uid'];
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //如果前一步骤的工序未全部完工不允许开工
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        $orderId = $orderInfo['id'];
        $foreignKey = intval($orderInfo['customer_order_id']);
        $order_title = $orderInfo['order_title'];

        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();
        if (in_array(3, $userRights)) {//有分配权限 1:查看;2:可写;3:分配;4:提交;5:转发;
            //判断是否发信息给下一道工艺的员工

            //添加预估时间&修改工单工序状态&修改主工单状态
            //获取对应工序信息
            $orderProcessObj = OrderProcess::where('id', $input['order_process_id'])->first();

            //        $orderProcessObj->estimated_time = $input['estimated_time'];
            $orderProcessObj->estimated_time_hour = $input['estimated_time_hour'];
            $orderProcessObj->estimated_time_minute = $input['estimated_time_minute'];
            $orderProcessObj->start_time = $curTime;
            $orderProcessObj->status = 2;
            $orderProcessObj->uid = $userId;
            $orderProcessObj->save();


            //更新管理员消息状态为1需分配(需原状态为1需接单)
            $typeUserId = $orderProcessObj->uid;
            $typeId = $orderProcessObj->id;
            UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 2);

            //修改工单列表关联表数据状态
            $type = 2;//工序工单
            $relateId = $orderProcessObj->id;
            $status = 2;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //工序管理员确认接单后，修改主工单状态
            $orderObj = Order::where('id', $orderId)->first();
            if ($orderObj->status == 1) {
                $orderObj->status = 101;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 101;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            }

        } else {//普通员工提交
            //获取前一步骤所有工艺
            $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
            //获取订单类型是否允许同时开工
            $orderTypeProcessId = OrderProcess::where('id', $orderProcessId)->first()->ordertype_process_id;
            $isMeanwhile = OrderType::isMeanwhileNextStep($orderTypeProcessId);

            if ($isMeanwhile) {
                //如果前面的工序已经开工则允许开工
                //前面的步骤待开工的数量（状态 1：待接单 2：待分派）
                $noStartProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
                if ($noStartProcessNum != 0) {
                    return [
                        'code' => 1,
                        'message' => '请等待上道工序开工'
                    ];
                }
            } else {
                //判断对应步骤的工艺是否都已经完成
                $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
                if ($noCompleteProcessNum != 0) {
                    return [
                        'code' => 1,
                        'message' => '请等待上道工序完工'
                    ];
                }
            }


            $orderProcessCourseObj = OrderProcessCourse::where('id', $input['order_process_id'])->first();
            //限制多次开工
            if ($orderProcessCourseObj->status != 1 && $orderProcessCourseObj->status != 2) {
                return [
                    'code' => 1,
                    'message' => '工单已经开工，请刷新页面'
                ];
            }

            //        $orderProcessCourseObj->estimated_time = $input['estimated_time'];
            //$overUserRow = DepartmentUser::getInfo(['user_id' => $orderProcessInfo['uid']])->toArray();

            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            //更新员工消息状态为2已接单(需原状态为1需接单)
            $courseUserId = $orderProcessCourseObj->uid;
            $courseId = $orderProcessCourseObj->id;
            UserMessage::updateTypeStatusByTypeId(1, $courseId, $courseUserId, 3);
            $courseUser = DepartmentUser::getCurrentInfo($courseUserId)->toArray();
            //员工给对应的管理员发一条开工消息
            //$typeUserId = $orderProcessInfo['uid'];
            $typeUserId = $orderProcessCourseObj->assign_id;
            $orderInfoProductNum = $orderInfo['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
            $orderInfoSpecification = $orderInfo['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }
            $fieldName23 = $this->changeFieldName23($orderInfo['field_name_23']);
            $messageContent = $processTitle . 'rnrn';
            $messageContent .= "单位名称：{$fieldName23}rnrn品名：{$orderInfo['product_name']}rnrn";
            $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
            $messageContent .= "交货日期：{$orderInfo['finished_date']}";
            $data = [
                'company_id' => $orderProcessInfo['company_id'], 'privilege_id' => '',
                'form_user_id' => $userId, 'to_user_id' => $typeUserId,
                'foreign_key' => $foreignKey,
                'type' => 3, 'type_id' => $courseId,
                'title' => $order_title, 'content' => $messageContent
            ];
            UserMessage::sendCustomerOrderMessage($data);

            //给下一工序的工序管理员和员工（如果已派发）发送消息
            //获取上一个部门&上一个部门
            $processOrderTypeObj = ProcessOrdertype::where(['id'=>$orderProcessInfo['ordertype_process_id']])->first();
            $stepNumber = false;
            if($processOrderTypeObj){
                $stepNumber = $processOrderTypeObj->step_number;
            }

            $nextProcessList = OrderType::getAllNextOrderTypeProcess($orderInfo['order_type'], $orderProcessInfo['process_type'],$stepNumber);
            foreach ($nextProcessList as $nextOrderTypeProcessId){
                //给工序管理员发送消息
                $tmpNextOrderProcessRow =  OrderProcess::where(['order_id'=>$orderId,'ordertype_process_id'=>$nextOrderTypeProcessId])->first()->toArray();
                $tmpNextOrderProcessId = $tmpNextOrderProcessRow['id'];
                $tmpNextOrderProcessUid = $tmpNextOrderProcessRow['uid'];

                $messageContent = "上一道工序【{$processTitle}】rnrn开工了";

                $data = [
                    'company_id' => $orderProcessInfo['company_id'],
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $tmpNextOrderProcessUid,
                    'foreign_key' => $foreignKey,
                    'type' => 9,
                    'type_id' => $orderProcessInfo['id'],
                    'title' => $order_title,
                    'content' => $messageContent
                ];
                UserMessage::sendCustomerOrderMessage($data);


                //给已经分派了员工工单的员工发送消息
                $tmpNextOrderProcessCourseList = OrderProcessCourse::where(['order_process_id'=>$tmpNextOrderProcessId])->get();
                foreach ($tmpNextOrderProcessCourseList as $tmpNextOrderProcessCourseRow){
                    $data = [
                        'company_id' => $orderProcessInfo['company_id'],
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $tmpNextOrderProcessCourseRow->uid,
                        'foreign_key' => $foreignKey,
                        'type' => 9,
                        'type_id' => $orderProcessInfo['id'],
                        'title' => $order_title,
                        'content' => $messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }
            }



            $orderProcessCourseObj->estimated_time_hour = $input['estimated_time_hour'];
            $orderProcessCourseObj->estimated_time_minute = $input['estimated_time_minute'];
            $orderProcessCourseObj->start_time = time();
            $orderProcessCourseObj->status = 3;
            $orderProcessCourseObj->uid = $userId;
            $orderProcessCourseObj->save();

            //修改工单列表关联表数据状态
            $type = 4;//工序工单
            $relateId = $orderProcessCourseObj->id;
            $status = 3;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //员工开工后，修改工序工单状态
            $orderProcessObj = OrderProcess::where('id', $orderProcessId)->first();
            if ($orderProcessObj->status == 1 || $orderProcessObj->status == 2 || $orderProcessObj->status == 101) {
                $orderProcessObj->status = 3;
                $orderProcessObj->save();

                //修改工单列表关联表数据状态
                $type = 2;
                $relateId = $orderProcessObj->id;
                $status = 3;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            }


            //员工开工后，修改主工单状态
            $orderObj = Order::where('id', $orderId)->first();
            if ($orderObj->status == 1 || $orderObj->status == 101) {
                $orderObj->status = 2;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 2;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

                //修改订单状态
                $customerOrderId = $orderObj->customer_order_id;
                \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId,4);//修改状态为生产中

            }
        }


        return '操作成功';
    }

    //确认开工后工单详情页面
    public function afterOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);


        //获取用户的权限
        $userId = Func::getHeaderValueByName('userid');
        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();
        if (count($userRights) == 1 && $userRights[0] == 1) {//只限制查看权限的用户
            //获取用户的角色id,角色例如为‘淋膜员工’
            $curUserInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            $privilegeId = $curUserInfo['privilege_id'];
            $processFieldList = PermissionEngine::getlookActionPrivilegeFieldsByProcessOrderType($orderInfo['order_type'], $orderProcessInfo['process_type'], $privilegeId);
        } else {
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
        }


        $apeList = [];
        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            $showTitle = '';
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);

            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];

        }

        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            //工单的需完成数量改为员工被派发的数量
            if ($input['order_process_course_id']) {
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }


            //版跳转问题
            $plateId = 0;
            if($tmpFiledType == 17 && $orderProcessInfo[$processFieldRow['field_name']]){
                $plateId = $orderProcessInfo[$processFieldRow['field_name']];
            }

            $apeList[] = [
                '$leftLabelValue' => $processFieldRow['title'],
                '$rightLabelValue' => $showTitle,
                '$plateId' => $plateId,
            ];
        }

        //追加需完成数量
        if ($orderProcessInfo['completed_number']) {
            $apeList[] = [
                '$leftLabelValue' => '需完成数量',
                '$rightLabelValue' => $orderProcessInfo['completed_number'],
            ];
        }


        //添加计件工资
        if(isset($orderProcessId,$privilegeId,$orderProcessCourseId)){
            $pieceWage= \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId,$privilegeId,$orderProcessCourseId);
            $apeList[] = [
                '$leftLabelValue' => '计件工资',
                '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
            ];
        }




        //返回ape填充数据
        $returnApe = [
            'pageID' => 8,
            'data' => [
                '$titleLabelValue' => $processTitle,
                '$commentValue' => $orderProcessInfo['remark'],
                '$list' => $apeList
            ]
        ];

        return $returnApe;
    }

    //领取材料页面基础页面
    public function confirmReceiveMaterialBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工单创建时设置的材料
        $fields = [
            'ygt_order_material_course.*',
            'ygt_product.product_name',
            'ygt_product.unit'
        ];
        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->leftJoin('ygt_product', 'ygt_order_material_course.material_id', '=', 'ygt_product.id')->select($fields)->get();
        $orderMaterialList = [];
        foreach ($orderMaterialCollection as $tmpRow) {
            $tmpOrderMaterialRow = $tmpRow->toArray();
            $tmpMateriaRow = ProductEngine::getProductInfoExist($tmpOrderMaterialRow['material_id']);
            if($tmpMateriaRow){
                $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
                $tmpOrderMaterialRow['is_trash'] = 0;
                $orderMaterialList[] = $tmpOrderMaterialRow;
            }else{
                //删除材料处理
                $tmpMateriaRow = ProductEngine::getProductInfoTrash($tmpOrderMaterialRow['material_id']);
                $tmpOrderMaterialRow['is_trash'] = 1;
                $tmpOrderMaterialRow['product_name'] = $tmpOrderMaterialRow['product_name']."[材料已删除]";

                $orderMaterialList[] = $tmpOrderMaterialRow;
            }
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $preOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $preProcess = Process::getOneValueById($preOrderProcessInfo['process_type'], 'title');
                $processIsSum = Process::getOneValueById($preOrderProcessInfo['process_type'], 'is_sum');

                $lastOrderProcessId = $preOrderProcessInfo['id'];
                if ($preOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {
                    //获取员工工单列表
                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $preOrderProcessInfo['id']])->get();
                    $finishNum = 0;
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = '' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                        }


                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }


                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                    }


                    if ($preOrderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }

                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
        }

        //获取领材是否需要扫码的配置
        $companyId = $orderInfo['company_id'];//厂id
        $isScanCode = Company::isScanCode($companyId);

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum;//上一工序完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序id
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['is_scan_code'] = $isScanCode;//是否需要扫码领取材料

        return $return;
    }

    //确认领取材料数量
    public function confirmReceiveMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//领取的材料id
        $input['receive_number'] = isset($input['receive_number']) ? $input['receive_number'] : '';//领取的材料数量

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //数据入库
        //工单材料表（修改操作，新加材料走其他接口）
        $orderMaterialCourseObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $input['material_id']])->first();
        $orderMaterialCourseObj->receive_number = $input['receive_number'];
        $orderMaterialCourseObj->save();

        //仓库材料库存表
//        Stock::OrderProcessStockOut($orderProcessCourseId);

        return '领取成功';
    }

    //添加材料
    public function addMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id
        $input['process_type'] = isset($input['process_type']) ? $input['process_type'] : '';//工单工序类型

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
//            'material_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
//            'material_id.required' => '缺少材料id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取用户id
        $userId = $orderProcessCourseRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //添加新材料到数据库
        $materialIdList = explode(',', $input['material_id']);
        foreach ($materialIdList as $materialId) {
            if (trim($materialId)) {
                $orderMaterialObj = OrderMaterialCourse::firstOrCreate(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialId, 'company_id' => $companyId], ['allow_delete' => 1]);
                /*$orderMaterialRow = [
                    'order_id' => $orderProcessInfo['order_id'],
                    'process_type' => $orderProcessInfo['process_type'],
                    'material_id' => $materialId,
                    'allow_delete' => 1,
                ];
                $orderMaterialObj->fill($orderMaterialRow);*/
//                $orderMaterialObj->save();
            }
        }
        return '添加成功';
    }

    //添加材料
    public function manageMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id
        $input['process_type'] = isset($input['process_type']) ? $input['process_type'] : '';//工单工序类型

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //添加新材料到数据库
        $materialIdList = explode(',', $input['material_id']);
        foreach ($materialIdList as $materialId) {
            if (trim($materialId)) {
                $orderMaterialObj = OrderMaterial::firstOrCreate(['order_id' => $orderProcessInfo['order_id'], 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialId], ['allow_delete' => 1]);
            }
        }
        //删除未传入材料的id的原纪录
        OrderMaterial::where(['order_id' => $orderProcessInfo['order_id'], 'process_type' => $orderProcessInfo['process_type']])->whereNotIn($materialIdList)->delete();

        return '添加成功';
    }

    //删除材料
    public function deleteMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
            'material_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
            'material_id.required' => '缺少材料id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();

        //添加新材料到数据库
        $orderMaterialObj = OrderMaterialCourse::firstOrNew(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $input['material_id']]);
        $orderMaterialObj->delete();
        return '删除成功';
    }


    //确认领取完成
    public function confirmReceiveComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $orderId = $orderProcessInfo['order_id'];
        $order = Order::where('id',$orderId)->first();
        $foreignKey = intval($order->customer_order_id);

        //如果材料有未领取不能完成
        $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
        if (!empty($orderMaterialList)) {

            $companyId = $messageContent = '';
            foreach ($orderMaterialList as $orderMaterialRow) {
                if (!$orderMaterialRow['receive_number']) {
                    return [
                        'code' => 1,
                        'message' => '请领取完材料'
                    ];
                }

                //判断库存数量是否足够
                $materialId = $orderMaterialRow['material_id'];
                $stockInfo = ProductEngine::getProductInfo($materialId);
                if ($stockInfo['number'] < $orderMaterialRow['receive_number']) {
                    return [
                        'code' => 1,
                        'message' => '材料' . $stockInfo['product_name'] . '库存不足'
                    ];
                }

                $companyId = $orderMaterialRow['company_id'];
                $messageContent .= ',' . $stockInfo['product_name'];
            }
            //员工领取材料发消息, 给指定角色发消息
            if ($companyId != '' && $messageContent != '') {
                $appnodeIdArr = [1, 3];//1下单人3库存管理人员
                $privilegeIdArr = [];
                foreach ($appnodeIdArr as $appnodeId) {
                    $tempPrivilegeIdArr = Privilege::getPrivilegeIds($companyId, $appnodeId);
                    foreach ($tempPrivilegeIdArr as $tempPrivilegeId) {
                        if (!in_array($tempPrivilegeId, $privilegeIdArr)) {
                            $privilegeIdArr[] = $tempPrivilegeId;
                        }
                    }
                }
                if ($privilegeIdArr) {
                    foreach ($privilegeIdArr as $messagePrivilegeId) {
                        $messageContent = '员工领取了' . $messageContent . '等材料';
                        $data = [
                            'company_id' => $companyId, 'privilege_id' => $messagePrivilegeId,
                            'form_user_id' => $orderProcessCourseRow['uid'], 'to_user_id' => '',
                            'foreign_key' => $foreignKey,
                            'type' => 12, 'type_id' => 0,
                            'title' => '领取材料', 'content' => $messageContent
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }
                }
            }

            //判断领取材料
            Stock::OrderProcessCourseStockOut($orderProcessCourseId);
        }

        //修改工单工序状态
        $orderProcessCourseObj = OrderProcessCourse::where('id', $orderProcessCourseId)->first();
        $orderProcessCourseObj->status = 1;
        $orderProcessCourseObj->receive_material_time = time();
        $orderProcessCourseObj->save();

        //修改工单列表关联表数据状态
        $type = 4;
        $relateId = $orderProcessCourseObj->id;
        $status = 1;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

        //修改消息状态
        $typeId = $orderProcessCourseObj->id;
        $typeUserId = $orderProcessCourseObj->uid;
        UserMessage::updateTypeStatusByTypeId(1, $typeId, $typeUserId, 1);

        //如果工序订单状态为接单，修改状态
        $orderProcessId = $orderProcessInfo['id'];
        $orderProcessObj = OrderProcess::where(['id' => $orderProcessId])->first();
        if ($orderProcessObj->status == 1) {
            // 修改工序工单状态为2（已接单）
            $orderProcessObj->status = 2;
            $orderProcessObj->save();
        }

        return '确认领取完成';

    }

    //确认完工基础页面信息
    public function confirmCompleteBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $inputType = isset($input['type']) ? $input['type'] : 0;

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $totalNumber = $orderProcessCourseRow['total_number'];
        $finishNumber = $orderProcessCourseRow['finish_number'];
        $wasteNumber = $orderProcessCourseRow['waste_number'];
        if (!$finishNumber) {
            $finishNumber = 0;
        }
        if (!$wasteNumber) {
            $wasteNumber = 0;
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();

        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工单创建时设置的材料
        $fields = [
            'ygt_order_material_course.*',
            'ygt_product.product_name'
        ];
        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->leftJoin('ygt_product', 'ygt_order_material_course.material_id', '=', 'ygt_product.id')->select($fields)->get();
        $orderMaterialList = [];
        foreach ($orderMaterialCollection as $tmpRow) {
            $tmpOrderMaterialRow = $tmpRow->toArray();
//            $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
            $tmpMateriaRow = ProductEngine::getProductInfoExist($tmpOrderMaterialRow['material_id']);
            if($tmpMateriaRow){
                $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
                $tmpOrderMaterialRow['is_trash'] = 0;
            }else{
                //删除材料处理
                $tmpMateriaRow = ProductEngine::getProductInfoTrash($tmpOrderMaterialRow['material_id']);
                $tmpOrderMaterialRow['is_trash'] = 1;
                $tmpOrderMaterialRow['product_name'] = $tmpOrderMaterialRow['product_name']."[材料已删除]";
            }


            if (!$tmpOrderMaterialRow['receive_number']) {
                $tmpOrderMaterialRow['receive_number'] = 0;
            }

            $tmpOrderMaterialRow['unit'] = $tmpMateriaRow['unit'];
            $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
            $orderMaterialList[] = $tmpOrderMaterialRow;
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }


        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $lastOrderProcessId = $orderProcessInfo['id'];

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加

                if ($orderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                    $finishNum = 0;

                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {


                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = date('Y年m月d日H时', $preProcessEstimatedTime);
                        }

                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                    }


                    if ($orderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }
                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
        }

        //分批提交数量展示
        $where = [
            ['order_process_course_id', '=', $orderProcessCourseId],
            ['submit_num', '>', 0],
        ];
        $orderProcessCourseGradationList = OrderProcessCourseGradation::where($where)->get();
        $submitList = [];
        foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
            $tmpArr = [
                'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                'submit_num' => $orderProcessCourseGradationRow['submit_num']
            ];
            $submitList[] = $tmpArr;
        }

        //分批提交废品数量展示
        $where = [
            ['order_process_course_id', '=', $orderProcessCourseId],
            ['submit_waste_num', '>', 0],
        ];
        $orderProcessCourseGradationList = OrderProcessCourseGradation::where($where)->get();
        $submitWasteList = [];
        foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
            $tmpArr = [
                'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                'submit_num' => $orderProcessCourseGradationRow['submit_waste_num']
            ];
            $submitWasteList[] = $tmpArr;
        }

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');


        //获取员工的角色id，判断是否需要输入件数 20180323
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $personnelId = $orderProcessCourseRow['uid'];
        $personnelRow = DepartmentUser::getCurrentInfo($personnelId)->toArray();
        $personnelPrivilegeId = $personnelRow['privilege_id'];

        $needPiece = OrderEngine::getPrivilegePiece($personnelPrivilegeId,$orderProcessInfo['ordertype_process_id']);


        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum;//上一工序完成数量
        $return['total_number'] = $totalNumber;//需完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['finish_number'] = $finishNumber;//已完成数量
        $return['waste_number'] = $wasteNumber;//已完成数量
        $return['submit_list'] = $submitList;//分次提交详情
        $return['submit_waste_list'] = $submitWasteList;//分次提交废品详情
        $return['needPiece'] = $needPiece;//是否需要填入件数
//        $return['type'] = $inputType;//0简单版1车间版
//        if($inputType==1)
//        {
//            $return['img_title'] = '共x' . $imgNum . '张图片';
//        }

        return $return;

    }


    //确认完工
    public function confirmComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $input['completed_number'] = isset($input['completed_number']) ? $input['completed_number'] : '';//完成数量
        $input['waste_number'] = isset($input['waste_number']) ? $input['waste_number'] : '';//废品数量
        $input['meter_counter'] = isset($input['meter_counter']) ? $input['meter_counter'] : '';//计米器图片
        $input['finish_number_piece'] = isset($input['finish_number_piece']) ? $input['finish_number_piece'] : '';//完成数量-件数
        $inputRemark = isset($input['remark']) ? $input['remark'] : '';//备注

        if ($input['material_list']) {
            $input['material_list'] = \GuzzleHttp\json_decode(htmlspecialchars_decode($input['material_list']), true);
        } else {
            $input['material_list'] = [];
        }

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        ////判断对应工序下是否有多个员工-- 20180228调整 一个员工也不需要限制完成数量&完成数量从分批提交的数中获取
//        $orderProcessCourseCout = OrderProcessCourse::where(['order_process_id' => $orderProcessCourseRow['order_process_id']])->get()->count();
//        if ($orderProcessCourseCout > 1) {
//            if (!$input['completed_number'] && $input['completed_number'] !== '0') {
//                return [
//                    'code' => 1,
//                    'message' => '请填写完成数量'
//                ];
//            }
//        } else {
//            if (!$input['completed_number']) {
//                return [
//                    'code' => 1,
//                    'message' => '请填写完成数量'
//                ];
//            }
//        }

//        if (!$input['waste_number'] && $input['waste_number'] !== '0') {
//            return [
//                'code' => 1,
//                'message' => '请填写废品数量'
//            ];
//        }

//        if ( ($input['completed_number']+$input['waste_number']) > $orderProcessCourseRow['total_number'] ) {
//            return [
//                'code' => 1,
//                'message' => '数量不能大于分派数量'
//            ];
//        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $curOrderProcessId = $orderProcessInfo['id'];
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        $order_title = $orderInfo['order_title'];
        $foreignKey = intval($orderInfo['customer_order_id']);
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');


        //如果上一部门没有完工，限制提交完工
        $orderProcessId = $orderProcessInfo['id'];
        //获取前一步骤所有工艺
        $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preOrderProcessList) {
            $preOrderProcessList = $preOrderProcessList->toArray();
        } else {
            $preOrderProcessList = [];
        }

        $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 3, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
        if ($noCompleteProcessNum) {
            return [
                'code' => 1,
                'message' => '请等待上道工序完工'
            ];
        }


        $retreatMaterialList = [];//记录退品信息
        //工单材料表添加剩余数量、废品数量
        if (!empty($input['material_list'])) {
            foreach ($input['material_list'] as $materialRow) {
                $orderMaterialObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialRow['material_id']])->first();
                if (!$materialRow['residual_number'] && $materialRow['residual_number'] !== '0') {
                    return [
                        'code' => 1,
                        'message' => '请填写余品数量'
                    ];
                }
                if (number_format($materialRow['residual_number']) > number_format($orderMaterialObj->receive_number)) {
                    return [
                        'code' => 1,
                        'message' => '余品数量不能超过领取材料总数'
                    ];
                }

                if (!$materialRow['scrap_number'] && $materialRow['scrap_number'] !== '0') {
                    return [
                        'code' => 1,
                        'message' => '请填写废品数量'
                    ];
                }
                if (number_format($materialRow['scrap_number']) > number_format($orderMaterialObj->receive_number)) {
                    return [
                        'code' => 1,
                        'message' => '废品数量不能超过领取材料总数'
                    ];
                }

                if (!$materialRow['retreat_number'] && $materialRow['retreat_number'] !== '0') {
                    return [
                        'code' => 1,
                        'message' => '请填写废品数量'
                    ];
                }

                if (number_format($materialRow['retreat_number']) > number_format($orderMaterialObj->receive_number)) {
                    return [
                        'code' => 1,
                        'message' => '退品数量不能超过领取材料总数'
                    ];
                }

                //如果有退品数量，记录数据，统一处理
                if($materialRow['retreat_number']){
                    $retreatMaterialList[] = $materialRow;
                }



                //增加废品总价
                $materialDetailInfo = ProductEngine::getProductInfo($materialRow['material_id']);//材料详细信息

                $orderMaterialObj->residual_number = $materialRow['residual_number'];
                $orderMaterialObj->scrap_number = $materialRow['scrap_number'];
                $orderMaterialObj->retreat_number = $materialRow['retreat_number'];
                $orderMaterialObj->scrap_price = $materialDetailInfo['price'] * $materialRow['scrap_number'];
                $orderMaterialObj->save();

            }
        }


        //修改员工工单工序状态
        $orderProcessCourseObj = OrderProcessCourse::where('id', $orderProcessCourseId)->first();
//        $orderProcessCourseObj->finish_number = $input['completed_number'];
        $orderProcessCourseObj->meter_counter = $input['meter_counter'];
        $orderProcessCourseObj->finish_number_piece = $input['finish_number_piece'];
//        $orderProcessCourseObj->waste_number = $input['waste_number'];
        $orderProcessCourseObj->status = 4;
        $orderProcessCourseObj->remark = $inputRemark;
        $orderProcessCourseObj->save();

        //更新员工给管理员发的那条消息状态为2已完工(需原状态为1生产中)
        $typeUserId = $orderProcessCourseObj->assign_id;
        $typeId = $orderProcessCourseId;
        UserMessage::updateTypeStatusByTypeId(3, $typeId, $typeUserId, 2);
        //更新员工的消息为已完工
        $courseUid = $orderProcessCourseObj->uid;
        UserMessage::updateTypeStatusByTypeId(1, $typeId, $courseUid, 4);

        //修改工单列表关联表数据状态
        $type = 4;
        $relateId = $orderProcessCourseObj->id;
        $status = 4;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

        //判断工单工序是否完成
        $noCompleteProcessCourseNum = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->where('status', '!=', 4)->count();
        if ($noCompleteProcessCourseNum == 0) {
            //工序完成时，统计工序总完成数量
            $processIsSum = Process::getOneValueById($orderProcessInfo['process_type'], 'is_sum');

            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
            $finishNum = 0;

            $finishUserNumList = [];
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $finishNum += $orderProcessCourseRow['finish_number'];
                if (!$processIsSum) {//不累加
                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (isset($finishUserNumList[$tmpPrivilegeId])) {
                        $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                    } else {
                        $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                    }
                }
            }

            //不累加--未完工时取完成量最小的员工
            if (!empty($finishUserNumList)) {
                $finishMinNum = '';
                foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                    if ($finishMinNum === 0) {//如果有员工完成数量为0，
                        break;
                    }

                    if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                        $finishMinNum = $finishUserNumRow['finish_number'];
                    }
                }
                $finishNum = $finishMinNum;
            }

            //如果版的使用记录
            $orderProcessObj = OrderProcess::where(['id' => $curOrderProcessId])->first();
            $companyId = $orderProcessObj->company_id;
            $orderId = $orderProcessObj->order_id;

            //获取字段信息
            $processFieldList = Process::getFieldListByProcessId($orderProcessObj->process_type);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
                if ($tmpFiledType == 17) {//添加关联关系
                    $tmpFiledName = $processFieldRow['field_name'];
                    if ($orderProcessObj->$tmpFiledName && is_numeric($orderProcessObj->$tmpFiledName)) {
                        //添加关联关系
                        $orderPlateObj = OrderPlate::firstOrNew(['id' => '']);
                        $insertRow = [];
                        $insertRow['order_id'] = $orderId;
                        $insertRow['order_process_id'] = $orderProcessObj->id;
                        $insertRow['plate_id'] = $orderProcessObj->$tmpFiledName;
                        $insertRow['company_id'] = $companyId;
                        $insertRow['number'] = $finishNum;

                        //获取需要存入表的关联字段
//                        $content = '';
//                        $orderPlateField = OrderEngine::getOrderPlateField();
//                        foreach ($orderPlateField as $item => $filedRow) {
//                            $fieldName = $filedRow['field'];
//                            if (!isset($orderProcessObj->$fieldName)) {
//                                $filedValue = '';
//                            } else {
//                                $filedValue = $orderProcessObj->$fieldName;
//                            }
//                            $content[$item] = $filedValue;
//                        }
//                        $insertRow['content'] = serialize($content);
                        
                        $orderPlateObj->fill($insertRow);
                        $orderPlateObj->save();

                        //修改版的数据
                        $plateObj = Plate::where(['id' => $orderProcessObj->$tmpFiledName])->first();
                        if ($plateObj) {
                            $plateObj->order_times = $plateObj->order_times + 1;
                            $plateObj->finish_number = $plateObj->finish_number + $finishNum;
                            $plateObj->last_time = time();
                            $plateObj->save();
                        }
                    }
                }
            }


            $orderProcessObj = OrderProcess::where('id', $orderProcessInfo['id'])->first();
            $orderProcessObj->status = 4;
            $orderProcessObj->save();

            //修改工单列表关联表数据状态
            $type = 2;
            $relateId = $orderProcessObj->id;
            $status = 4;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);


            ////判断是否发信息给下一道工艺的员工
            //获取当前步骤所有工艺
            $curOrderProcessList = OrderType::getCurrentOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
            //判断当前步骤的工艺是否都已经完成
            $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $curOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noCompleteProcessNum == 0) {
                $userRow = DepartmentUser::getCurrentInfo($orderInfo['uid'])->toArray();
                //推送消息
                //获取下一步骤所有工序
                $nextProcessList = OrderType::getAllNextOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
                if (!empty($nextProcessList)) {

                    ////流程调整后，不需要在订单完成后给下一个工序的相关人员发送消息
                }


                ////如果当前阶段工序都已经完成且无下一阶段的工序，主工单状态设置为完成 -- 逻辑调整，所有工单都完成后主订单才算完成20180209
                //获取未完工的工序工单的数量
                $where = [
                    ['order_id', '=', $orderProcessInfo['order_id']],
                    ['status', '!=', 4],
                ];
                $orderProcessNoCompleteNum = OrderProcess::where($where)->get()->count();

                if ($orderProcessNoCompleteNum == 0) {

                    $orderObj = Order::where('id', $orderProcessInfo['order_id'])->first();
                    $orderObj->status = 3;
                    $orderObj->save();
                    $orderId = $orderObj->id;

                    //修改工单列表关联表数据状态
                    $type = 1;
                    $relateId = $orderObj->id;
                    $status = 3;
                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

                    //修改订单状态
                    $customerOrderId = $orderObj->customer_order_id;
                    \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId,5);//修改状态为已完工


                    //工单完成后给相关角色发送报表
                    //获取报表列表
                    $companyId = $orderInfo['company_id'];
                    $orderReportTypeList = OrderReportType::where(['company_id' => $companyId])->get();
                    foreach ($orderReportTypeList as $orderReportTypeRow) {
                        $orderReportTypeId = $orderReportTypeRow['id'];
                        //存入工单报表关联表
                        $orderReport = OrderReport::firstOrNew(['id' => '']);
                        $orderReportRow = [
                            'order_id' => $orderInfo['id'],
                            'order_report_type_id' => $orderReportTypeId,
                            'company_id' => $companyId
                        ];
                        $orderReport->fill($orderReportRow);
                        $orderReport->save();
                        $orderReportId = $orderReport->id;

                        //发送消息给相关人员
                        $privilegeIds = $orderReportTypeRow['send_user'];
                        $privilegeIdList = explode(',', $privilegeIds);
                        foreach ($privilegeIdList as $privilegeId) {
                            if ($privilegeId) {
                                $data = [
                                    'company_id' => $companyId, 'privilege_id' => $privilegeId,
                                    'form_user_id' => $orderProcessCourseRow['uid'], 'to_user_id' => '',
                                    'foreign_key' => $foreignKey,
                                    'type' => 11, 'type_id' => $orderReportId,
                                    'title' => $orderInfo['order_title'], 'content' => '有个工单完工了，请查看详情'
                                ];
                                UserMessage::sendCustomerOrderMessage($data);
                            }
                        }
                    }

                }
            }
        }


        //退品材料发送消息给采购员
        if(!empty($retreatMaterialList)){
            $messageContent = "工单中有退品rnrn";
            $messageContent .= "以下材料有退品：rnrn";

            foreach ($retreatMaterialList as $retreatMaterialRow){
                $tmpMaterialId = $retreatMaterialRow['material_id'];
                $tmpMaterialRetreatNum = $retreatMaterialRow['retreat_number'];

                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                $tmpMaterialName = $tmpMaterialRow['product_name'];
                $tmpMaterialUnit = $tmpMaterialRow['unit'];

                $messageContent .= "{$tmpMaterialName} 退 {$tmpMaterialRetreatNum}（{$tmpMaterialUnit}）rnrn";

            }

            //发送消息给采购员
            $purchasingAgentPrivilegeList         = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 10 );
            foreach ($purchasingAgentPrivilegeList as $purchasingAgentPrivilegeId){
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $purchasingAgentPrivilegeId,
                    'form_user_id' => $orderProcessCourseRow['uid'],
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 20,//发送给采购员的消息
                    'type_id' => $orderInfo['id'],
                    'title' => $orderInfo['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }

        }




        //剩余材料仓库入库
//        Stock::OrderProcessStockIn($orderProcessCourseId);
        if (!empty($input['material_list'])) {//如果没有取材料不走出入库方法
            Stock::OrderProcessCourseStockIn($orderProcessCourseId);
        }
        return '确认完工';
    }

    //确认完工详情页
    public function completeOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];

            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }


        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $apeList = [];

        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            $showTitle = '';
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);

            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];

        }


        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            if ($tmpFiledType == 4) {//材料选择暂时不显示在
                continue;
            }

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            if ($input['order_process_course_id']) {//员工查看分配自己
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }

            $apeList[] = [
                '$leftLabelValue' => $processFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];
        }

        //添加计件工资
        if(isset($orderProcessId,$privilegeId,$orderProcessCourseId)){
            $pieceWage= \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId,$privilegeId,$orderProcessCourseId);
            $apeList[] = [
                '$leftLabelValue' => '计件工资',
                '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
            ];
        }



        //材料领取
        $apeList1 = [];
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            $finishNum = 0;//已完成数量
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                $finishNum += $orderProcessCourseRow['finish_number'];
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
            $finishNum = $orderProcessCourseRow['finish_number'];//已完成数量
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            //获取材料信息
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            //废品率
            $userNum = $orderMaterialRow['receive_number'] - $orderMaterialRow['residual_number'];
            if ($userNum) {
                $rejectRate = (round($orderMaterialRow['scrap_number'] / $userNum * 100, 4)) . '%';
            } else {
                $rejectRate = 0;
            }


            $apeList1[] = [
                '$fistVlaue0' => $orderMaterialRow['receive_number'],
                '$fistVlaue1' => $orderMaterialRow['residual_number'],
                '$fistVlaue2' => $orderMaterialRow['scrap_number'],
                '$fitsTitleVlaue0' => '数量',
                '$fitsTitleVlaue1' => '数量',
                '$fitsTitleVlaue2' => '数量',
                '$secondTitleValue0' => '单位',
                '$secondTitleValue1' => '单位',
                '$secondTitleValue2' => '单位',
                '$secondValue0' => $materialRow['unit'],
                '$secondValue1' => $materialRow['unit'],
                '$secondValue2' => $materialRow['unit'],
                '$statusValue0' => '已领取',
                '$statusValue1' => '余品数',
                '$statusValue2' => '废品数',
                '$lose' => $rejectRate,
                '$productName' => $materialRow['product_name']
            ];
        }

        $returnApe = [
            'pageID' => 2,
            'data' => [
                '$commentValue' => $orderProcessInfo['remark'],
                '$titleLabelValue' => $processTitle,
                '$numberOfDoneValue' => $finishNum,
                '$list' => $apeList,
                '$list1' => $apeList1
            ]
        ];

        return $returnApe;
    }

    //工序信息获取统一接口
    public function getProcessDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//工单工序类型id
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//工单工序类型id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单id 测试数据1
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的工单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱工单id 测试数据

        $curOrderProcessRow = OrderProcessPre::where(['order_id' => $input['order_id'], 'process_type' => $input['process_id']])->first();
        if ($curOrderProcessRow) {
            $curOrderProcessRow = $curOrderProcessRow->toArray();
        } else {
            $curOrderProcessRow = [];
        }

        if ($pre_order_id) {
            $curOrderProcessRow = OrderProcessPre::where(['order_id' => $pre_order_id, 'process_type' => $input['process_id']])->first();
            if ($curOrderProcessRow) {
                $curOrderProcessRow = $curOrderProcessRow->toArray();
            }
            $input['order_id'] = $pre_order_id;
        } elseif ($input['copy_order_id']) {//如果传入复制工单id
            if (OrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first()) {
                $curOrderProcessRow = OrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first()->toArray();
            } else {
                $curOrderProcessRow = [];
            }
        }


        //获取工单信息
        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        //通过工序id，获取对应的字段
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);
        //如果是第一道工序，添加字段需完成数量----功能调整取消这一段
//        $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//        if (in_array(d['process_id'], $processFirstList)){
//            $processFieldList[]=[
//                'id'=>0, 'field_name'=>'completed_number', 'title'=>'需完成数量', 'field_type'=>1, 'text_type'=>1,
//                'placeholder'=>'请填写', 'is_must'=>1, 'relation_id'=>0,'field_unit'=>[],'data'=>[]
//            ];
//        }

        //获取工序信息
        $processTitle = Process::getOneValueById($input['process_id'], 'title');

        //是否为工艺上最后一个工序
        $orderTypeObj = new OrderType();
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        }


        $buttonTitle = '';
        if ($nextProcessId) {
            $buttonTitle = '下一步';//按钮显示文字
        } else {
            $buttonTitle = '确认提交';//按钮显示文字
        }

        //获取工艺数目
        $curProcessNum = OrderType::getOrderTypeProcessNumber($orderType, $input['process_id']);

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        //添加默认值
        if (!empty($curOrderProcessRow)) {
            foreach ($processFieldList as $key => $row) {
                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);

                        $materialList = [];
                        foreach ($materialIdList as $materialId) {
                            $materiaRow = ProductEngine::getProductInfo($materialId);
                            if ($materiaRow) {//过滤异常情况
                                $materiaRow->toArray();
                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materiaRow['product_no'],
                                    'product_name' => $materiaRow['product_name'],
                                ];
                            }
                        }
                        $processFieldList[$key]['default_product_list'] = $materialList;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }

                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }


                }
            }
        }

        //追加再基础信息中填写的客户id
        $customerId = '';
        if (isset($orderInfo['customer_name']) && $orderInfo['customer_name'] && $orderInfo['customer_name'] != '(null)') {
            $customerId = $orderInfo['customer_name'];
        }

        $return = [];
        $return['customer_id'] = $customerId;//基础信息的工序id
        $return['process_title'] = $processTitle;//工序名称
        $return['process_field_list'] = $processFieldList;//工序字段
        $return['button_title'] = $buttonTitle;//按钮显示文字
        $return['create_order_title'] = '创建工单（' . ($curProcessNum + 1) . '/' . ($processNum + 1) . '）';//按钮显示文字

        return $return;
    }

    //工序提交统一接口
    public function processSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//工单工序类型
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//工单工序类型关联id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $processFieldList = Process::getFieldListByProcessId($input['process_id']);
            //如果是第一个工序，添加字段‘需完成数量’--功能调整取消这一段
//            $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
//            $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//            if (in_array($input['process_id'], $processFirstList)){
//                $processFieldList[]=[
//                    'id'=>0, 'field_name'=>'completed_number', 'title'=>'需完成数量', 'field_type'=>1, 'text_type'=>1,
//                    'placeholder'=>'请填写', 'is_must'=>1, 'relation_id'=>0,'field_unit'=>[],'data'=>[]
//                ];
//            }

            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($processFieldList as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }
        //$this->validateRequestParameters($input, $processFieldRules, true, $processFieldMessage);

        //获取用户id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取工序所包含的字段
        $processFieldList = Process::getFieldArrByProcessId($input['process_id']);

        //数据入库
        //存入印刷工序提交的数据
        $orderProcessPreRow = OrderProcessPre::firstOrNew(['order_id' => $input['order_id'], 'process_type' => $input['process_id']]);

        $insertRow = [
            'order_id' => $input['order_id'],//关联的工单id
            'process_type' => $input['process_id'],//工序类型
            'ordertype_process_id' => $input['ordertype_process_id'],//工序工单类型关联id
            'company_id' => $companyId,
        ];


        //如果是第一道工序，添加字段需完成数量--功能调整,第一个工序需完成数量取产品的数量
        //调整为所有工序需完成数量都由工单产品数量挂钩

        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first();
//        $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//        if (in_array($input['process_id'], $processFirstList)) {
        //获取工单基础信息设置的数量
        $tmpArr = explode(',', $orderInfo['product_num']);
        $productNum = $tmpArr[0];
        if (!$productNum || !is_numeric($productNum)) {
            $productNum = 0;
        }
        $insertRow['completed_number'] = $productNum;
//        }

        foreach ($processFieldList as $processField) {
            $insertRow[$processField] = $input[$processField];
        }

        $orderProcessPreRow->fill($insertRow);
        $orderProcessPreRow->save();

        //如果是最后一道工序，工单创建完成
        //获取工单信息
        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        $orderTypeObj = new OrderType();
        $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
            $nextOrdertypeProcessId = $nextOrderTypeProcessRow[0]['id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
            $nextOrdertypeProcessId = '';
        }

        if ($nextProcessId || $input['is_draft']) {//有下一步或者是退出保存操作
            if ($nextProcessId) {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                    'next_process_id' => $nextProcessId,//下一道工序的id
                    'next_ordertype_process_id' => $nextOrdertypeProcessId,//下一道工序的工序工单类型关联id
                ];
            } else {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                ];
            }
            return $return;
        } else {//提交生成正式工单
            $orderId = $this->orderCreate($input['order_id']);

            $return = [
                'is_final' => 1,//是否为最后一道工序
                'message' => '创建成功',//提示信息
                'order_id' => $orderId,//创建成功的工单id
                'order_type' => $orderType,//创建成功的工单工序类型
            ];
            return $return;
        }
    }

    //管理员工单详情
    public function getManagerOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id


        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();
        //获取工序名称
//        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
//        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';

        $tabviewSource = [];//对应页面上纵向列表
        $tabviewSource[] = [
            'idName' => 27,
            '$littleTimeValue' => date('H:i', $orderInfo['created_at']),
            '$otherTimeValue' => date('Y-m-d', $orderInfo['created_at']),
            '$seeDetaileFunctionName' => '',
            '$departmentManageValue' => '已下单，待处理',
            '$userManageValue' => '',
            '$workMachineValue' => '',
            '$lookDetaileButtonHiden' => 1,
            '$userManageHiden' => 1,
            '$workMachineHiden' => 1,
            '$planTimeValue' => '',
            '$planTimeHiden' => 1
        ];//对应页面上纵向列表


        $list = [];//对应页面上横向列表
        $list[] = [
            '$statusValue' => '',
            '$departmentValue' => '待处理',
            '$leftHiden' => 1,
            '$rightHiden' => 0,
            '$statusHiden' => 1,
            '$departmentFontColor' => $blueColor,
            '$statusViewBG' => $blueColor,
            '$statusViewBorderColor' => $blueColor,
            '$androidBg' => $androidBgBlue
        ];//默认自带条目

        foreach ($orderProcessList as $processId) {
            //获取工序信息
//            if (!OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
//                dd(['order_id' => $orderInfo['id'], 'process_type' => $processId]);
//            }
            if (!$orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
                continue;
            }

            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();


            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            //是否显示预估时间
            if ($orderProcessInfo['status'] == 1 || $orderProcessInfo['status'] == 4) {
                $planTimeValue = '';
                $planTimeHiden = 1;
            } else {
                if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                    $planTimeValue = '';
                } else {
                    $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                }
                $planTimeHiden = 1;
            }

            //已完成状态可以查看
            $lookDetaileButtonHiden = 0;
            $buttontitle = '查看';
            $seeDetaileFunctionName = 'seeDetaileAction';

            ////判断下一个工序是否需要工序管理员分派
            ////如果该工序没有设置工序管理员&未分派
            $privilegeAssignmentIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderInfo['order_type'], $processId, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
            if ($orderProcessInfo['uid']) {
                $userInfo = DepartmentUser::getCurrentInfo($orderProcessInfo['uid'])->toArray();
                $showUserName = $userInfo['truename'];
            } else {
                $showUserName = '';
            }

            if (!$privilegeAssignmentIds->count()) {//工序没有设置工序管理员
                //工单操作改为员工

                //没有配置工序管理员&员工还未分派工单
                $orderProcessCourse = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                if (!$orderProcessCourse->count()) {//表示未分派
                    $buttontitle = '分派';
                    $seeDetaileFunctionName = 'goSendAction';
                    $showUserName = '无';
                } else {
                    $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourse->first()->uid)->toArray();
                    $showUserName = $userInfo['truename'];
                    if ($orderProcessCourse->count() > 1) {
                        $showUserName .= '等';
                    }
                }
            }

            if ($orderProcessInfo['status']) {//待接单状态不显示 调整--待接单状态也显示 20180305 18:30
                //获取对应用户信息
                //$userInfo = DepartmentUser::getInfo(['user_id' => $orderProcessInfo['uid']])->toArray();
                //统计完工数量

                //调整-预计完成时间调整为从员工工单获取
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                $finishNum = 0;

                $processId = $orderProcessInfo['process_type'];
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $processIsSum = $process['is_sum'];//工序数量是否累加0不累加1累加

                $finishUserNumList = [];
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                    //设定的角色不进行统计数量到工序数量中
                    //过滤异常数据
                    if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                        continue;
                    }
                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                        continue;
                    }

                    $finishNum += $orderProcessCourseRow['finish_number'];
                    if (!$processIsSum) {//不累加
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];

                        if (isset($finishUserNumList[$tmpPrivilegeId])) {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                        } else {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                        }
                    }
                }

                //不累加--未完工时取完成量最小的员工
                if (!empty($finishUserNumList)) {
                    $finishMinNum = '';
                    foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                        if ($finishMinNum === 0) {//如果有员工完成数量为0，
                            break;
                        }

                        if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                            $finishMinNum = $finishUserNumRow['finish_number'];
                        }
                    }
                    $finishNum = $finishMinNum;
                }


                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => date('H:i', $orderProcessInfo['updated_at']),
                    '$otherTimeValue' => date('Y-m-d', $orderProcessInfo['updated_at']),
                    '$departmentManageValue' => '[处理部门]' . $processTitle,
                    '$userManageValue' => '处理人:' . $showUserName,
                    '$workMachineValue' => '完成数量' . $finishNum,//操作机 =>03
                    '$seeDetaileFunctionName' => $seeDetaileFunctionName . $orderProcessInfo['id'],
                    '$lookDetaileButtonHiden' => $lookDetaileButtonHiden,
                    '$buttontitle' => $buttontitle,
                    '$userManageHiden' => 0,
                    '$workMachineHiden' => 0,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => $planTimeHiden
                ];

            }

            $statusArray = [
                '1' => '待接单',
                '2' => '待分派',
                '3' => '生产中',
                '4' => '已完成',
                '101' => '待开工',
            ];
//            if($orderProcessInfo['status'] == 2 || $orderProcessInfo['status'] == 3){
            if (isset($orderProcessInfo['status']) && $orderProcessInfo['status'] && $orderProcessInfo['status'] != 1 && $orderProcessInfo['status'] != 101 && $orderProcessInfo['status'] != 2) {
                $statusValue = $statusArray[$orderProcessInfo['status']];
                $useColor = $blueColor;
                $androidBg = $androidBgBlue;
                $statusHiden = 0;
                $leftHiden = 0;
                $rightHiden = 0;
            } else {
                $statusValue = '';
                $useColor = $greColor;
                $androidBg = $androidBgGrey;
                $statusHiden = 1;
                $leftHiden = 0;
                $rightHiden = 0;
            }


            $list[] = [
                '$statusValue' => $statusValue,//'生产中'
                '$departmentValue' => $processTitle,//'彩印部门'
                '$leftHiden' => $leftHiden,
                '$rightHiden' => $rightHiden,
                '$statusHiden' => $statusHiden,
                '$departmentFontColor' => $useColor,
                '$statusViewBG' => $useColor,
                '$statusViewBorderColor' => $useColor,
                '$androidBg' => $androidBg
            ];
        }

        if ($orderInfo['status'] == 3) {//已经完成
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $blueColor;
            $androidBg = $androidBgBlue;
            $statusHiden = 0;
            $leftHiden = 0;
            $rightHiden = 1;
        } else {
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $greColor;
            $androidBg = $androidBgGrey;
            $statusHiden = 1;
            $leftHiden = 0;
            $rightHiden = 1;
        }
        $list[] = [
            '$statusValue' => $statusValue,//'生产中'
            '$departmentValue' => $processTitle,//'彩印部门'
            '$leftHiden' => $leftHiden,
            '$rightHiden' => $rightHiden,
            '$statusHiden' => $statusHiden,
            '$departmentFontColor' => $useColor,
            '$statusViewBG' => $useColor,
            '$statusViewBorderColor' => $useColor,
            '$androidBg' => $androidBg
        ];

        $tabviewSource = array_reverse($tabviewSource);
        //获取工序对应的详细信息
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $returnApe = [
            'pageID' => 4,
            'data' => [
                '$productImage' => $exampleImg,
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$imageClickFunctionName' => 'imageClickAction' . $orderInfo['id'],
                '$lookOrderDetaileFunctionName' => 'lookOrderDetaile' . $orderInfo['id'],
                '$tabviewSource' => $tabviewSource,
                '$list' => $list
            ]
        ];
        return $returnApe;
    }

    //管理员工单详情-多工序列表展示
    public function getManagerOrderDetailList(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id

        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //工单基础信息字段，目前格式固定
        $orderBaseFieldList = $this->orderBaseFieldList();

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            if ($row['field_type'] == 9) {//图片处理
                continue;//先不处理
            } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                $rightLabelValue = $orderInfo[$row['field_name']];
                $tmpArr = explode(',', $rightLabelValue);
                $rightLabelValue = '';
                foreach ($tmpArr as $tmpValue) {
                    $rightLabelValue .= $tmpValue;
                }
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                continue;//另外处理
            } elseif ($row['field_type'] == 6) {//开关按钮
                $rightLabelValue = $orderInfo[$row['field_name']];
                $rightLabelValue = ($rightLabelValue == 1) ? '是' : '否';
            } else {
                $rightLabelValue = $orderInfo[$row['field_name']];
            }
            $baseInfoList[] = [
                '$leftLabelValue' => $leftLabelValue,
                '$rightLabelValue' => $rightLabelValue
            ];
        }
        //追加配送地址
        $orderDistributionRow = OrderDistribution::where(['order_id' => $input['order_id']])->first();
        if (!empty($orderDistributionRow)) {
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人',
                '$rightLabelValue' => $orderDistributionRow['consignee']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人-手机号',
                '$rightLabelValue' => $orderDistributionRow['phone']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '区县地址',
                '$rightLabelValue' => $orderDistributionRow['province_name'] . ' ' . $orderDistributionRow['city_name'] . ' ' . $orderDistributionRow['area_name']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人详细地址',
                '$rightLabelValue' => $orderDistributionRow['address']
            ];
        }

        $listAll[] = [
            '$titleLabelValue' => '基本信息',
            '$list' => $baseInfoList
        ];

        //动态获取工序数据
        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息
            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    continue;
                }

                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);


                $list[] = [
                    '$leftLabelValue' => $processFieldRow['title'],
                    '$rightLabelValue' => $showTitle,
                ];
            }
            $listAll[] = [
                '$titleLabelValue' => $processTitle,
                '$list' => $list
            ];
        }

        $returnApe = [
            'pageID' => 1,
            'data' => [
                '$listAll' => $listAll
            ]
        ];
        return $returnApe;
    }


    //工单派发(下单人给工序管理员)
    public function orderConfirmAssignment()
    {
        $orderIds = request('order_ids');//工单id
        $orderIdArr = explode(",", $orderIds);
        $assignUser = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user')), true);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //分配结果
        foreach ($orderIdArr as $orderId) {
            if (!trim($orderId)) {//过滤空格，不考虑orderId为0
                continue;
            }
            //获取工单详情
            $tmpOrderObj = Order::where(['id' => $orderId])->first();

            //只允许未派单的工单派发
            if ($tmpOrderObj->status != 4) {
                return [
                    'code' => 1,
                    'msg' => '工单已派发，请刷新页面'
                ];
            }

            $tmpOrderRow = $tmpOrderObj->toArray();
            $orderTitle = $tmpOrderRow['order_title'];
            $orderTypeId = $tmpOrderRow['order_type'];
            $companyId = $tmpOrderRow['company_id'];
            $foreignKey = intval($tmpOrderRow['customer_order_id']);

            //限制重复分派工单
            $isAllAssign = 1;//是否都已经派发
            $orderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($orderProcessList as $orderProcessRow) {
                if (!$orderProcessRow['uid']) {
                    $isAllAssign = 0;
                }
            }

            if ($isAllAssign) {
                return [
                    'code' => 1,
                    'msg' => '工单已派发，请刷新页面'
                ];
            }


            //下单人给管理员发消息
            $orderInfoProductNum = $tmpOrderRow['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
            $orderInfoSpecification = $tmpOrderRow['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }

            ////追加功能，给没有设置分派角色的工序增加默认工序管理员（下单人）
            $result = OrderType::getAllStepsWithDistribution($tmpOrderRow['order_type']);
            //获取工序可分派给工序管理员的列表
            $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
                $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
                $process_id = $item->process_id;
                $distributionUser->transform(function ($item) use ($process_id) {
                    $item->process_id = $process_id;
                    $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                    return $item;
                });
                $item->distributionUser = $distributionUser->toArray();
                return $item;
            });

            $noAssignProcessIdList = [];//无需分派的工序id列表
            foreach ($result as $tmpValue) {
                if (empty($tmpValue['distributionUser'])) {
                    $noAssignProcessIdList[] = $tmpValue['process_id'];
                    //先分配工单给自己
                    $orderProcessCollectionList = OrderProcess::where(['order_id' => $orderId, 'process_type' => $tmpValue['process_id']])->get();
                    foreach ($orderProcessCollectionList as $orderProcessCollectionRow) {
                        $orderProcessCollectionRow->uid = $tmpOrderRow['uid'];
                        $orderProcessCollectionRow->save();
                    }
                }
            }

            //分配用户
            foreach ($assignUser as $assignUserRow) {
                $tmpProcessId = $assignUserRow['process_id'];
                $orderProcess = OrderProcess::firstOrNew(['order_id' => $orderId, 'process_type' => $tmpProcessId]);
                if ($orderProcess->count()) {
                    $uid = $assignUserRow['uid'];
                    $orderProcess->uid = $uid;
                    $orderProcess->save();
                }
            }

            //获取下单人信息
            $userRow = DepartmentUser::getCurrentInfo($tmpOrderRow['uid'])->toArray();

            //获取第一道步骤涉及的工序
            $processFirstList = OrderType::getFirstProcessBag($tmpOrderRow['order_type'])->toArray();
            //获取工单对应的工单工序列表
            $tmpOrderProcessList = OrderProcess::where(['order_id' => $orderId])->get();

            $needNextAssign = 0;//是否需要下一步分派（分派员工工单）
            foreach ($tmpOrderProcessList as $tmpOrderProcessRow) {
                //获取工序对应的权限用户
                $processId = $tmpOrderProcessRow['process_type'];

                ////调整为分派完订单同时发消息
//                if (in_array($tmpOrderProcessRow['process_type'], $processFirstList)) {//给第一道工艺的人发信息
                ////调整为下单人也需要分派指定员工（再下一步进行派发）--20180301 16:44
                if (in_array($tmpOrderProcessRow['process_type'], $noAssignProcessIdList)) {//未分派工序管理员，直接分派给员工
                    $needNextAssign = 1;

                    //自动派发给员工的订单不修改订单状态为已接单
                    //调整：无工序管理员订单，员工开工后再修改工序订单状态,订单状态修改为待开工
//                        //修改工序工单状态为2（已接单）
//                        $tmpOrderProcessRow->status = 101;
//                        $tmpOrderProcessRow->save();

                } else {//分派给工序管理员
                    //存入工单列表关联表
                    OrderEngine::importProcessManagerOrder($tmpOrderProcessRow->toArray());
                    $fieldName23 = $this->changeFieldName23($tmpOrderRow['field_name_23']);
                    $messageContent = "单位名称：{$fieldName23}rnrn品名：{$tmpOrderRow['product_name']}rnrn";
                    $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
                    $messageContent .= "交货日期：{$tmpOrderRow['finished_date']}rnrn";

                    //追加材料消息
                    $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($tmpOrderProcessRow['id']);
                    if(!empty($materialIdList)){
                        $messageContent .= "工单需使用以下材料：rnrn";
                        //获取所有材料信息
                        foreach($materialIdList as $tmpMaterialId){
                            //获取材料信息
                            $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                            $tmpMaterialName = $tmpMaterialRow['product_name'];
                            $tmpMaterialNum = $tmpMaterialRow['number'];
                            $tmpMaterialUnit = $tmpMaterialRow['unit'];

                            $messageContent .= "{$tmpMaterialName} {$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                        }
                    }



                    $data = [
                        'company_id' => $tmpOrderProcessRow['company_id'],
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $tmpOrderProcessRow['uid'],
                        'foreign_key' => $foreignKey,
                        'type' => 2,
                        'type_id' => $tmpOrderProcessRow['id'],
                        'title' => $orderTitle,
                        'content' => $messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }

                //给此步骤有查看权限的人发消息
                $processId = $tmpOrderProcessRow['process_type'];
                $orderTypeId = $tmpOrderRow['order_type'];
                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;

                //存入工单列表关联表
                OrderEngine::importProcessSeeOrder($tmpOrderProcessRow->toArray(), $privilegeIds);

                //批量给所有角色发
                $fieldName23 = $this->changeFieldName23($tmpOrderRow['field_name_23']);
                $messageContent = "单位名称：{$fieldName23}rnrn品名：{$tmpOrderRow['product_name']}rnrn";
                $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
                $messageContent .= "交货日期：{$tmpOrderRow['finished_date']}";
                foreach ($privilegeIds as $val) {
                    $data = [
                        'company_id' => $tmpOrderProcessRow['company_id'], 'privilege_id' => $val,
                        'form_user_id' => $userId, 'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 9, 'type_id' => $tmpOrderProcessRow['id'],
                        'title' => $orderTitle, 'content' => $messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }

//                }
            }

            ////调整-如果还有员工需分派，主工单状态先不调整
            if (!$needNextAssign) {
                //修改工单状态
                $tmpOrderObj->status = 1;
                $tmpOrderObj->save();

                //修改订单状态
                $customerOrderId = $tmpOrderObj->customer_order_id;
                \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId,3);//修改状态为待生产

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $tmpOrderObj->id;
                $status = 1;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
                OrderEngine::changeMainOrderTime($relateId, time());
            }


        }

        //判断是否是订单转工单
        $isCustomerOrderToOrder = 0;//是否是订单转工单 1-是 0-不是
        if(isset($tmpOrderRow['customer_order_id']) && $tmpOrderRow['customer_order_id']){
            $isCustomerOrderToOrder = 1;
        }

        return [
            'code' => 0,
            'msg' => '操作成功',
            'need_next_assign' => $needNextAssign, //是否需要下一步分派 0-不需要 1-需要
            'isCustomerOrderToOrder' => $isCustomerOrderToOrder,//是否是订单转工单 1-是 0-不是
        ];
    }

    //下单人给分派员工工单-基础页面
    public function manageOrderCourseAssignment()
    {
        $orderTypeId = request('order_type');

        $result = OrderType::getAllStepsWithDistribution($orderTypeId);

        $result = $result->filter(function ($item) {
            if ($item->distribution->toArray()) {
                return false;
            } else {
                return true;
            }
        });

        $result->transform(function ($item) {

            $tijiaoPrivilegeIds = PermissionEngine::getStepActionPrivilegeIds(4, $item->id);

            $distributionUser = DepartmentUser::getWithPrivilege($tijiaoPrivilegeIds);

            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->user = $distributionUser->toArray();
            return $item;
        });

        return $result->values();

    }

    //下单人给分派员工工单-提交
    public function manageOrderCourseAssignmentSubmit()
    {

        $orderId = request('order_id');//工单id
        $assignUser = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user')), true);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //分配结果
        //获取工单详情
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderTitle = $orderRow['order_title'];
        $orderTypeId = $orderRow['order_type'];
        $companyId = $orderRow['company_id'];
        $foreignKey = $orderRow['customer_order_id'];

        //只允许未派单的工单派发
        if ($orderRow['status'] != 4) {
            return [
                'code' => 1,
                'msg' => '工单已派发，请刷新页面'
            ];
        }

        //分配员工
        foreach ($assignUser as $assignUserRow) {
            $processId = $assignUserRow['process_id'];
            $orderProcessRow = OrderProcess::where(['order_id' => $orderId, 'process_type' => $processId])->first()->toArray();
            $orderProcessId = $orderProcessRow['id'];

            $processId = $orderProcessRow['process_type'];//工序id
            $orderMaterialList = OrderMaterial::where(['order_id' => $orderId, 'process_type' => $processId])->get()->toArray();

            //只有工序工单状态为1或2时才允许派发工单
            if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1) {
                return [
                    'code' => 1,
                    'message' => '工单已派发，请刷新工单列表'
                ];
            }

            //获取用户id
            $uidList = explode(',', $assignUserRow['uid']);
            foreach ($uidList as $uid) {
                if (!$uid) {//空值过滤
                    continue;
                }

                $insertRow = [
                    'uid' => $uid,
                    'total_number' => 0,
                    'order_process_id' => $orderProcessId,
                    'assign_id' => $userId,//派发人id
                    'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
//                    'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 临时调整-跳过领材阶段
                    'company_id' => $orderProcessRow['company_id'],//状态 1-待接单
                ];

                $orderProcessCourse = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessId, 'uid' => $uid]);
                $orderProcessCourse->fill($insertRow);
                $orderProcessCourse->save();
                $orderPorcessCourseId = $orderProcessCourse->id;

                ////材料添加到员工材料表
                foreach ($orderMaterialList as $orderMaterialRow) {
                    $orderMaterialCourse = OrderMaterialCourse::firstOrNew(['id' => '']);
                    unset($orderMaterialRow['order_id']);
                    unset($orderMaterialRow['uid']);
                    $orderMaterialRow['order_process_course_id'] = $orderPorcessCourseId;

                    $orderMaterialCourse->fill($orderMaterialRow);
                    $orderMaterialCourse->save();
                }

                //管理员给员工发消息
                $assignUserRow = DepartmentUser::getCurrentInfo($userId)->toArray();
                $orderInfoProductNum = $orderRow['product_num'];
                $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
                $orderInfoSpecification = $orderRow['finished_specification'];
                if ($orderInfoSpecification) {
                    $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                    $orderInfoSpecification .= '厘米';
                }
                $fieldName23 = $this->changeFieldName23($orderRow['field_name_23']);
                $messageContent = "单位名称：{$fieldName23}rnrn品名：{$orderRow['product_name']}rnrn";
                $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
                $messageContent .= "交货日期： {$orderRow['finished_date']}";

                //追加材料消息
                $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($orderProcessRow['id']);
                if(!empty($materialIdList)){
                    $messageContent .= "工单需使用以下材料：rnrn";
                    //获取所有材料信息
                    foreach($materialIdList as $tmpMaterialId){
                        //获取材料信息
                        $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                        $tmpMaterialName = $tmpMaterialRow['product_name'];
                        $tmpMaterialNum = $tmpMaterialRow['number'];
                        $tmpMaterialUnit = $tmpMaterialRow['unit'];

                        $messageContent .= "{$tmpMaterialName} {$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                    }
                }


                $data = [
                    'company_id' => $orderProcessRow['company_id'],
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $uid,
                    'foreign_key' => $foreignKey,
                    'type' => 1,
                    'type_id' => $orderPorcessCourseId,
                    'title' => $orderTitle,
                    'content' => $messageContent,
                    'type_status' => 2,
                ];
                $result = UserMessage::sendCustomerOrderMessage($data);

                //存入工单列表关联表
                OrderEngine::importProcessCourseOrder($orderProcessCourse->toArray());
            }

            //修改工单状态
            $orderProcess = OrderProcess::where(['id' => $orderProcessId])->first();
//        $orderProcess->status = 3;
            $orderProcess->status = 101;//增加新状态待开工
            $orderProcess->save();

            //修改工单列表关联表数据状态
            $type = 2;
            $relateId = $orderProcess->id;
//        $status = 3;
            $status = 101;//增加新状态待开工
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //如果下单人直接派发员工--修改主工单状态
            if ($orderRow['uid'] == $orderProcess['uid']) {
                //修改工单状态
                $orderObj = Order::where(['id' => $orderId])->first();
                if (!empty($orderObj->toArray())) {
                    $orderObj->status = 1;
                    $orderObj->save();

                    //修改订单状态
                    $customerOrderId = $orderObj->customer_order_id;
                    \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId,3);//修改状态为待生产

                    //修改工单列表关联表数据状态
                    $type = 1;
                    $relateId = $orderObj->id;
                    $status = 1;
                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
                } else {
                    return [
                        'code' => 1,
                        'message' => '参数错误'
                    ];
                }
            }

            //更新工序管理员消息状态为3已分配待开工
            $typeUserId = $orderProcess->uid;
            $typeId = $orderProcess->id;
            UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 3);
        }


        //修改工单状态
        $tmpOrderObj = Order::where(['id' => $orderId])->first();
        $tmpOrderObj->status = 1;
        $tmpOrderObj->save();

        //修改工单列表关联表数据状态
        $type = 1;
        $relateId = $tmpOrderObj->id;
        $status = 1;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
        OrderEngine::changeMainOrderTime($relateId, time());

        ;
        //判断是否是订单转工单
        $isCustomerOrderToOrder = 0;//是否是订单转工单 1-是 0-不是
        if(isset($orderRow['customer_order_id']) && $orderRow['customer_order_id']){
            $isCustomerOrderToOrder = 1;
        }


        return [
            'code' => 0,
            'message' => '分派成功',
            'isCustomerOrderToOrder' => $isCustomerOrderToOrder,//是否是订单转工单 1-是 0-不是
        ];

    }

    //工单删除
    public function orderDelete()
    {
        $orderIds = request('order_ids');//工单id
        $orderIdArr = explode(",", $orderIds);
        foreach ($orderIdArr as $orderId) {
            if (!trim($orderId)) {//过滤空格，不考虑orderId为0
                continue;
            }

            //删除工单列表表的数据
            OrderListRelation::where(['type' => 1, 'relate_id' => $orderId])->delete();
            $orderProcessIds = OrderProcess::where(['order_id' => $orderId])->get()->pluck('id');
            OrderListRelation::whereIn('type', [2, 3])->whereIn('relate_id', $orderProcessIds)->delete();
            //删除和该订单有关的所有消息
            $whereMessage = ['foreign_type' => 1, 'foreign_key' => $orderId];
            UserMessage::where($whereMessage)->delete();


            //删除主工单信息
            Order::where(['id' => $orderId])->delete();
            //删除工单派送信息
            OrderDistribution::where(['order_id' => $orderId])->delete();
            //删除工单工序信息
            OrderProcess::where(['order_id' => $orderId])->delete();

            //删除工单和版关联关系
            OrderPlate::where(['order_id' => $orderId])->delete();


        }

        return [
            'code' => 0,
            'msg' => '操作成功'
        ];
    }

    //工单再来一单
    public function copyOrder()
    {
        $oldOrderId = request('order_id');//旧工单id

        if (!$oldOrderId) {
            return [
                'code' => 1,
                'message' => '参数错误'
            ];
        }

        $curOrderRow = Order::where(['id' => $oldOrderId])->first()->toArray();

        //创建预生成工单&返回预生成工单id
        $orderPreRow = OrderPre::firstOrNew(['id' => '']);

        //生成工单号
        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);

        //用户id&企业id
        //$userId = request()->header('userid', 0);
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $insertRow = [
            'order_type' => $curOrderRow['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
        ];

        $orderPreRow->fill($insertRow);
        $orderPreRow->save();
        $orderPreId = $orderPreRow->id;

        //复制对应的工单派送地址
        $curOrderDistributionCollection = OrderDistribution::where(['order_id' => $curOrderRow['id']])->get();
        if ($curOrderDistributionCollection->count()) {//存在派送信息
            $curOrderDistributionCollectionRow = $curOrderDistributionCollection->first()->toArray();
            $curOrderDistributionCollectionRow['order_id'] = $orderPreId;
            $orderDistributionPreRow = OrderDistributionPre::firstOrNew(['id' => '']);
            $orderDistributionPreRow->fill($curOrderDistributionCollectionRow);
            $orderDistributionPreRow->save();
            $orderDistributionPreId = $orderDistributionPreRow->id;
        }

        return ['order_id' => $orderPreId];

    }

    //分派员工列表
    public function orderCourseAssignment()
    {
        //获取基本参数
        $orderPorcessId = request('order_process_id');//工单工序id
        $orderProcessRow = OrderProcess::where(['id' => $orderPorcessId])->first()->toArray();


        $orderId = $orderProcessRow['order_id'];//工单id
        $processId = $orderProcessRow['process_type'];//工序id

        //获取工单信息
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderType = $orderRow['order_type'];//工单类型

        //获取对应分配员工列表
        $privilegeId = PermissionEngine::getStepSubmitActionPrivilegeIds($orderType, $processId)->toArray();//角色id
        $userList = DepartmentUser::getListByPrivilegeId($privilegeId)->toArray();//被分配的员工列表

        return [
            'completed_number' => $orderProcessRow['completed_number'],//需完成数量（分派数量）
            'userList' => $userList,
        ];
    }

    //分派员工-数据提交（工序管理员分派给员工）
    public function orderCourseAssignmentSubmit()
    {
        //获取基本参数
        $orderProcessId = request('order_process_id');//工单id
        $assignUserList = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user_list')), true);


        ////获取选中的员工&分派的数量
        //获取工单工序材料列表
        $orderProcessRow = OrderProcess::where(['id' => $orderProcessId])->first()->toArray();
        //用户id
        $userId = $orderProcessRow['uid'];

        $orderId = $orderProcessRow['order_id'];//工单id
        $processId = $orderProcessRow['process_type'];//工序id
        $orderMaterialList = OrderMaterial::where(['order_id' => $orderId, 'process_type' => $processId])->get()->toArray();

        //是否为重新分派
        $isReset = request('is_reset');//是否为重新分派 1-是 0-不是
        if ($isReset) {//如果是重新分派，清除原来的员工工单消息
            if ($orderProcessRow['status'] == 3 || $orderProcessRow['status'] == 4) {//如果工序工单已经开工，限制重新分派
                return [
                    'code' => 2,
                    'message' => '员工已开工，限制重新分派给员工'
                ];
            } else {//清除原来的员工工单
                $where = [
                    'order_process_id' => $orderProcessId
                ];
                $orderProcessCourseObjList = OrderProcessCourse::where($where)->get();
                foreach ($orderProcessCourseObjList as $orderProcessCourseObj) {
                    //清理工单列表表的数据
                    $where = [
                        'type' => 4,
                        'relate_id' => $orderProcessCourseObj->id
                    ];
                    $orderListRelationObjList = OrderListRelation::where($where)->get();
                    foreach ($orderListRelationObjList as $orderListRelationObj) {
                        $orderListRelationObj->delete();
                    }

                    //清理消息
                    $userId = $orderProcessCourseObj->uid;
                    $type = 1;
                    $typeId = $orderProcessCourseObj->id;
                    $result = UserMessage::deleteOneByTypeId($userId, $type, $typeId);

                    $orderProcessCourseObj->delete();
                }
            }
        } else {//如果不是重新派发，限制重复派发（多次点击或者网络原因）
            if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1) {
                return [
                    'code' => 1,
                    'message' => '工单已派发，请刷新页面'
                ];
            }
        }

        //只有工序工单状态为2时才允许派发工单
        if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1 && $orderProcessRow['status'] != 101) {
            return [
                'code' => 1,
                'message' => '工单已派发，请刷新工单列表'
            ];
        }

        //工单信息
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderTitle = $orderRow['order_title'];
        $foreignKey = intval($orderRow['customer_order_id']);

        //插入数据
        foreach ($assignUserList as $userRow) {
            $insertRow = [
                'uid' => $userRow['uid'],
                'total_number' => $userRow['total_number'],
                'order_process_id' => $orderProcessId,
                'assign_id' => $userId,//派发人id
                'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
//                'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 临时调整-跳过领材阶段
                'company_id' => $orderRow['company_id'],//状态 1-待接单
            ];

            $orderProcessCourse = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessId, 'uid' => $userRow['uid']]);
            $orderProcessCourse->fill($insertRow);
            $orderProcessCourse->save();
            $orderPorcessCourseId = $orderProcessCourse->id;

            ////材料添加到员工材料表
            foreach ($orderMaterialList as $orderMaterialRow) {
                $orderMaterialCourse = OrderMaterialCourse::firstOrNew(['id' => '']);
                unset($orderMaterialRow['order_id']);
                unset($orderMaterialRow['uid']);
                $orderMaterialRow['order_process_course_id'] = $orderPorcessCourseId;

                $orderMaterialCourse->fill($orderMaterialRow);
                $orderMaterialCourse->save();
            }


            //管理员给员工发消息
            $assignUserRow = DepartmentUser::getCurrentInfo($userId)->toArray();
            $orderInfoProductNum = $orderRow['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
            $orderInfoSpecification = $orderRow['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }
            $fieldName23 = $this->changeFieldName23($orderRow['field_name_23']);
            $messageContent = "单位名称：{$fieldName23}rnrn品名：{$orderRow['product_name']}rnrn";
            $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
            $messageContent .= "交货日期： {$orderRow['finished_date']}";

            //追加材料消息
            $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($orderProcessRow['id']);
            if(!empty($materialIdList)){
                $messageContent .= "工单需使用以下材料：rnrn";
                //获取所有材料信息
                foreach($materialIdList as $tmpMaterialId){
                    //获取材料信息
                    $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                    $tmpMaterialName = $tmpMaterialRow['product_name'];
                    $tmpMaterialNum = $tmpMaterialRow['number'];
                    $tmpMaterialUnit = $tmpMaterialRow['unit'];

                    $messageContent .= "{$tmpMaterialName} {$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                }
            }
            $data = [
                'company_id' => $orderProcessRow['company_id'],
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $userRow['uid'],
                'foreign_key' => $foreignKey,
                'type' => 1,
                'type_id' => $orderPorcessCourseId,
                'title' => $orderTitle,
                'content' => $messageContent,
                'type_status' => 2,
            ];
            UserMessage::sendCustomerOrderMessage($data);

            //存入工单列表关联表
            OrderEngine::importProcessCourseOrder($orderProcessCourse->toArray());
        }

        //修改工单状态
        $orderProcess = OrderProcess::where(['id' => $orderProcessId])->first();
//        $orderProcess->status = 3;
        $orderProcess->status = 101;//增加新状态待开工
        $orderProcess->save();

        //修改工单列表关联表数据状态
        $type = 2;
        $relateId = $orderProcess->id;
//        $status = 3;
        $status = 101;//增加新状态待开工
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

        //如果下单人直接派发员工--修改注定点状态
        if ($orderRow['uid'] == $orderProcess['uid']) {
            //修改工单状态
            $orderObj = Order::where(['id' => $orderId])->first();
            if (!empty($orderObj->toArray())) {
                $orderObj->status = 1;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 1;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            } else {
                return [
                    'code' => 1,
                    'message' => '参数错误'
                ];
            }
        }

        //更新管理员消息状态为3已分配待开工(需原状态为2需分配)
        $typeUserId = $orderProcess->uid;
        $typeId = $orderProcess->id;
        UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 3);

        return [
            'code' => 0,
            'message' => '分派成功'
        ];
    }


    //分派用户工单详情页面(厂长接单页面)
    public function getOrderDetailAssignment(Request $request)
    {
//        //获取传入数据
//        $input = $request->all();
//        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
//
//        //校验参数
//        $rules = [
//            'order_process_id' => 'required',
//        ];
//        $messages = [
//            'order_process_id.required' => '缺少工单id',
//        ];
//        $this->validateRequestParameters($input, $rules, true, $messages);
//
//        //获取对应工序信息
//        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
//        //获取工单信息
//        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
//        //获取工序名称
//        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
//        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
//
//        $apeList = [];
//        foreach ($processFieldList as $processFieldRow) {
//            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
//                continue;
//            }
//
//            //通过字段类型不同处理
//            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
//            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name']);
//            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
//            if ($tmpFiledType == 5) {//有单位 数量+单位
//                $tmpArr = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
//                $showNum = $tmpArr[0];
//                $unitId = $tmpArr[1];
//                $showTitle = $showNum . ' ' . $unitId;
//            } elseif ($tmpFiledType == 4) {//材料选择暂时不显示在
//                continue;
//            }
//
//            $apeList[] = [
//                '$leftLabelValue' => $processFieldRow['title'],
//                '$rightLabelValue' => $showTitle,
//            ];
//        }
//
//        //处理图片数据
//        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
//        $exampleImg = '';
//        foreach ($imgIdList as $imgId) {
//            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
//                continue;
//            }
//            if (!$exampleImg) {//取第一张图作为示例图
//                $exampleImg = ImgUpload::getImgUrlById($imgId);
//            }
//        }
//        //获取上一个部门&上一个部门
//        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
//        //获取预估完成时间最晚的一个，待开工的部门优先级最高
//        $preProcess = '';//上一个工序（部门）
//        $preProcessEstimatedTime = 0;
//        $preProcessEstimatedTimeStr = '';
//        if ($preProcessList) {
//            foreach ($preProcessList as $processId) {
//                //获取工序信息
//                $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
//                if ($orderProcessInfo['status'] == 1) {//待开工
//                    $preProcess = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
//                    $preProcessEstimatedTimeStr = '待开工';
//                    break;
//                } else {
//                    $tmpPreProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;
//                    if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
//                        $preProcess = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
//                        $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
//                        $preProcessEstimatedTimeStr = date('Ymd H:i:s', $preProcessEstimatedTime);
//                    }
//                }
//            }
//        } else {
//            $preProcess = '无';//上一个工序（部门）
//            $preProcessEstimatedTimeStr = '';
//        }
//
//        //返回数据
//        //厂长接单页面（工单待接单）
//        if ($orderProcessInfo['status'] == 1) {
//            $returnOrderInfo = [];
//            $returnOrderInfo['pageID'] = 2;
//            $returnOrderInfo['data'] = [
//                '$productNameValue' => $orderInfo['product_name'],
//                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
//                '$productTimeValue' => '交货日期:' . $orderInfo['finished_date'],
//                '$futureTimeValue' => $preProcessEstimatedTimeStr,
//                '$prevDepartmentValue' => $preProcess,
//                '$titleLabelValue' => $processTitle,
//                '$list' => $apeList,
//                '$commentValue' => $orderProcessInfo['remark'],
//                '$buttonTitleValue' => '确认接单',
//                '$sureButtonFunctionName' => 'orderSureAction' . $orderProcessInfo['id'],
//                '$imageClick' => 'imageClickAction' . $orderProcessInfo['id'],
//                '$productImagrUlr' => $exampleImg
//            ];
//        } else {
//
//
//        }
//
//        return $returnOrderInfo;
    }

    //查看被分配员工信息页面（工序管理员查看接单员工详情页面）
    public function getOrderDetailCourseAssignment()
    {
        //获取基础参数
        $orderProcessCourseId = request('order_process_course_id');
        if (!$orderProcessCourseId) {
            return [
                'code' => 1,
                'msg' => '参数错误'
            ];
        }
        //获取员工工单信息
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        //获取工序工单信息
        $orderProcessRow = OrderProcess::where(['id' => $orderProcessCourseRow['order_process_id']])->first()->toArray();
        //获取工单信息
        $orderRow = Order::where(['id' => $orderProcessRow['order_id']])->first()->toArray();


        //处理图片数据
        $imgIdList = explode(',', $orderRow['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderRow['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';

        $tabviewSource = [];//对应页面上纵向列表
        $tabviewSource[] = [
            'idName' => 27,
            '$littleTimeValue' => !empty($orderProcessCourseRow['created_at']) ? date('H:i', $orderProcessCourseRow['created_at']) : '',
            '$otherTimeValue' => !empty($orderProcessCourseRow['created_at']) ? date('Y-m-d', $orderProcessCourseRow['created_at']) : '',
            '$seeDetaileFunctionName' => '',
            '$departmentManageValue' => '已下单，待处理',
            '$userManageValue' => '',
            '$workMachineValue' => '',
            '$lookDetaileButtonHiden' => 1,
            '$userManageHiden' => 1,
            '$workMachineHiden' => 1,
            '$planTimeValue' => '',
            '$planTimeHiden' => 1
        ];


        $list = [];//对应页面上横向列表
        $list[] = [
            '$statusValue' => '',
            '$departmentValue' => '待开工',
            '$leftHiden' => 1,
            '$rightHiden' => 0,
            '$statusHiden' => 1,
            '$departmentFontColor' => $blueColor,
            '$statusViewBG' => $blueColor,
            '$statusViewBorderColor' => $blueColor,
            '$androidBg' => $androidBgBlue
        ];//默认自带条目

        //通过工单不同状态展示不同页面
        if ($orderProcessCourseRow['status'] == 1) {//待接单状态
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];
            //待接单状态无信息--已调整
        } elseif ($orderProcessCourseRow['status'] == 2) {//确认开工-未领取材料 调整：未领取材料待开工
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
//            //预估时间
//            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
//            //处理人信息
//            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['start_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['start_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime),
//                '$planTimeHiden' => 0
//            ];
        } elseif ($orderProcessCourseRow['status'] == 3) {//已领取材料
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;

            if ($estimatedTime < 631152000) {//过滤1970的情况
                $planTimeValue = '';
            } else {
                $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime);
            }


            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];

            //如果没有开始时间就不展示
            if ($orderProcessCourseRow['start_time']) {
                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => !empty($orderProcessCourseRow['start_time']) ? date('H:i', $orderProcessCourseRow['start_time']) : '',
                    '$otherTimeValue' => !empty($orderProcessCourseRow['start_time']) ? date('Y-m-d', $orderProcessCourseRow['start_time']) : '',

                    '$seeDetaileFunctionName' => '',
                    '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
                    '$userManageValue' => '',
                    '$workMachineValue' => '',
                    '$lookDetaileButtonHiden' => 1,
                    '$userManageHiden' => 1,
                    '$workMachineHiden' => 1,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => 0
                ];
            }

        } elseif ($orderProcessCourseRow['status'] == 4) {//确认完工
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;


            if ($estimatedTime < 631152000) {//过滤1970的情况
                $planTimeValue = '';
            } else {
                $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime);
            }

            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];

            //如果没有开始时间就不展示
            if ($orderProcessCourseRow['start_time']) {
                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => date('H:i', $orderProcessCourseRow['start_time']),
                    '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['start_time']),
                    '$seeDetaileFunctionName' => '',
                    '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
                    '$userManageValue' => '',
                    '$workMachineValue' => '',
                    '$lookDetaileButtonHiden' => 1,
                    '$userManageHiden' => 1,
                    '$workMachineHiden' => 1,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => 0
                ];
            }

            $tabviewSource[] = [
                'idName' => 27,
                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['updated_at']),
                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['updated_at']),
                '$seeDetaileFunctionName' => '',
                '$departmentManageValue' => '已完成',
                '$userManageValue' => '',
                '$workMachineValue' => '',
                '$lookDetaileButtonHiden' => 1,
                '$userManageHiden' => 1,
                '$workMachineHiden' => 1,
                '$planTimeValue' => '',
                '$planTimeHiden' => 1
            ];

        } else {
            return [
                'code' => 1,
                'msg' => '员工工单状态异常'
            ];
        }

        $tabviewSource = array_reverse($tabviewSource);
        //获取工序对应的详细信息
        $returnApe = [
            'pageID' => 14,
            'data' => [
                '$productImage' => $exampleImg,
                '$productNameValue' => $orderRow['product_name'],
                '$productOrderValue' => '生产单号:' . $orderRow['order_title'],
                '$imageClickFunctionName' => 'imageClickAction' . $orderRow['id'],
                '$lookOrderDetaileFunctionName' => 'lookOrderDetaile' . $orderRow['id'],
                '$tabviewSource' => $tabviewSource,
                '$list' => $list
            ]
        ];
        return $returnApe;
    }

    //工单各类型数量接口
    public function getOrderAllTypeNum()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //附加功能，将不预期保留的草稿箱数据删除 调整，只删除10分钟前的数据
        $allDeleteTime = time() - 60 * 10;
        $where = [
            ['company_id', '=', $companyId],
            ['uid', '=', $userId],
            ['is_trash', '=', 1],
            ['created_at', '<', $allDeleteTime]
        ];
        OrderPre::where($where)->delete();


        //待派单数量
        $noAssignOrdderNum = Order::where(['company_id' => $companyId, 'status' => 4, 'uid' => $userId])->get()->count();

        //已派单数量
        $isAssignOrdderNum = Order::where(['company_id' => $companyId, 'uid' => $userId])->where('status', '!=', '4')->get()->count();

        //草稿箱数量
        $draftOrderNum = OrderPre::where(['company_id' => $companyId, 'uid' => $userId])->get()->count();

        return [
            'no_assign_ordder_num' => $noAssignOrdderNum,//待派单数量
            'is_assign_ordder_num' => $isAssignOrdderNum,//已派单数量
            'draft_order_num' => $draftOrderNum,//草稿箱数量
        ];
    }

    //工单详情新接口-未完工
    public function getOrderDetailNewNoComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $dataList = [];
        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
            if ($tmpFiledType == 5) {//有单位 数量+单位
                if ($orderProcessInfo[$processFieldRow['field_name']]) {
                    $tmpArr = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    $showNum = $tmpArr[0];
                    if (isset($tmpArr[1])) {
                        $unitId = $tmpArr[1];
                    } else {
                        $unitId = '';
                    }
                    $showTitle = $showNum . ' ' . $unitId;
                } else {
                    $showTitle = '';
                }
            } elseif ($tmpFiledType == 6) {//开关
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']] ? '是' : '否';
            } elseif ($tmpFiledType == 4) {//材料选择
                continue;
            }

            if ($processFieldRow['field_name'] == 'completed_number') {//未完工时不显示完工数量
                continue;
            }

            $dataList[] = [
                'title' => $processFieldRow['title'],
                'value' => $showTitle,
            ];
        }

        //材料领取
        $materialList = [];
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            $materialList[] = [
                'material_id' => $materialRow['id'],//材料id
                'product_name' => $materialRow['product_name'],//材料名称
                'product_no' => $materialRow['product_no'],//材料编号
                'receive_number' => $orderMaterialRow['receive_number'],//领取数量
            ];
        }

        return [
            'title' => $processTitle,
            'dataList' => $dataList,
            'remark' => $orderProcessInfo['remark'],
            'materialList' => $materialList,
        ];
    }

    //工单详情新接口-已完工
    public function getOrderDetailNewComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $dataList = [];
        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
            if ($tmpFiledType == 5) {//有单位 数量+单位
                if ($orderProcessInfo[$processFieldRow['field_name']]) {
                    $tmpArr = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    $showNum = $tmpArr[0];
                    if (isset($tmpArr[1])) {
                        $unitId = $tmpArr[1];
                    } else {
                        $unitId = '';
                    }
                    $showTitle = $showNum . ' ' . $unitId;
                } else {
                    $showTitle = '';
                }
            } elseif ($tmpFiledType == 6) {//开关
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']] ? '是' : '否';
            } elseif ($tmpFiledType == 4) {//材料选择
                continue;
            }

            if ($input['order_process_course_id']) {//员工查看分配自己
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }

            $dataList[] = [
                'title' => $processFieldRow['title'],
                'value' => $showTitle,
            ];
        }

        //材料领取
        $materialList = [];
        $meterCounterImgList = [];//计米器图片列表
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            $finishNum = 0;//已完成数量
            $wasteNum = 0;//废品数量
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                $finishNum += $orderProcessCourseRow['finish_number'];
                $wasteNum += $orderProcessCourseRow['waste_number'];

                //记录计米器图片
                if ($orderProcessCourseRow['meter_counter']) {
                    $meterCounterImg = ImgUpload::getImgUrlById($orderProcessCourseRow['meter_counter']);
                    if ($meterCounterImg) {
                        $meterCounterImgList[] = $meterCounterImg;
                    }
                }
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
            $finishNum = $orderProcessCourseRow['finish_number'];//已完成数量
            $wasteNum = $orderProcessCourseRow['waste_number'] ? $orderProcessCourseRow['waste_number'] : 0;//过滤null

            //记录计米器图片
            if ($orderProcessCourseRow['meter_counter']) {
                $meterCounterImg = ImgUpload::getImgUrlById($orderProcessCourseRow['meter_counter']);
                if ($meterCounterImg) {
                    $meterCounterImgList[] = $meterCounterImg;
                }
            }
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            //获取材料信息
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            //废品率
            $userNum = $orderMaterialRow['receive_number'] - $orderMaterialRow['residual_number'];
            if ($userNum) {
                $rejectRate = (round($orderMaterialRow['scrap_number'] / $userNum * 100, 4)) . '%';
            } else {
                $rejectRate = 0;
            }

            $materialList[] = [
                'material_id' => $materialRow['id'],//材料id
                'product_name' => $materialRow['product_name'],//材料名称
                'product_no' => $materialRow['product_no'],//材料编号
                'unit' => $materialRow['unit'],//材料单位
                //图片
                //库存
                //
                'receive_number' => $orderMaterialRow['receive_number'],//领取数量
                'residual_number' => $orderMaterialRow['residual_number'],//余品数量
                'scrap_number' => $orderMaterialRow['scrap_number'],//废品数量
                'rejectRate' => $rejectRate,//废品率
            ];
        }

        //计算成品废品率
        $wasteRate = (round(($wasteNum / ($finishNum + $wasteNum)), 4) * 100) . '%';

        return [
            'title' => $processTitle,
            'dataList' => $dataList,
            'remark' => $orderProcessInfo['remark'],
            'materialList' => $materialList,
            'meterCounterImgList' => $meterCounterImgList,
            'finishNum' => $finishNum,
            'wasteNum' => $wasteNum,
            'wasteRate' => $wasteRate,
        ];
    }

    //下单人工单分配类型
    public function getOrderManageAssignmentType()
    {
        $orderId = request('order_id', '');

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取工单信息
        $orderInfo = Order::where('id', $orderId)->first()->toArray();
        $orderTypeId = $orderInfo['order_type'];

        $result = OrderType::getAllStepsWithDistribution($orderTypeId);
        //获取工序可分派给工序管理员的列表
        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        //判断工单类型对应的工序里是否有设置工序管理员
        $needAssignmentProcess = false;//需要工序分派
        foreach ($result as $tmpValue) {
            if (!empty($tmpValue['distributionUser'])) {
                $needAssignmentProcess = true;
            }
        }


        if ($needAssignmentProcess) {
            //如果已经派发了工序管理员（中途退出了，直接进入派发工序管理员页面）
            $isAllAssign = 1;//是否都已经派发
            $orderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($orderProcessList as $orderProcessRow) {
                if (!$orderProcessRow['uid']) {
                    $isAllAssign = 0;
                }
            }

            if ($isAllAssign) {
                return [
                    'type' => 4,//直接派发工单给员工
                    'order_type' => $orderTypeId,//订单类型id
                ];
            }

            return [
                'type' => 1,//正常流程
                'order_type' => $orderTypeId,//正常流程
            ];


        } else {
            //先分配工单给自己
            $orderProcessCollectionList = OrderProcess::where(['order_id' => $orderId])->get();
            foreach ($orderProcessCollectionList as $orderProcessCollection) {
                $orderProcessCollection->uid = $userId;
                $orderProcessCollection->save();

                //存入工单列表关联表
                OrderEngine::importProcessManagerOrder($orderProcessCollection->toArray());
            }

            ////调整-所有工序的订单一次性分派完成 20180208 | 调整-不再直接分派给员工，需要下单人分派给指定员工

            return [
                'type' => 4,//直接派发工单给员工
                'order_type' => $orderTypeId,//订单类型id
            ];


            //第一个工序分派给员工
//            $processFirstList = OrderType::getFirstProcessBag($orderTypeId)->toArray();
//            $processFirstList = OrderType::getAllOrderTypeProcess($orderTypeId)->toArray();
//            foreach ($processFirstList as $processId) {
//                $orderProcessRow = OrderProcess::where(['order_id' => $orderId, 'process_type' => $processId])->first();
//                $processId = $orderProcessRow['process_type'];
//                //获取有提交权限的角色id
//                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 4); //1:查看;2:可写;3:分配;4:提交;5:转发;
//                //获取角色下的用户id
//                $userList = DepartmentUser::getWithPrivilege($privilegeIds);
//
//                //给此步骤有查看权限的人发消息
//                $processId = $orderProcessRow['process_type'];
//                $orderTypeId = $orderInfo['order_type'];
//                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;
//
//                //存入工单列表关联表
//                OrderEngine::importProcessSeeOrder($orderProcessRow->toArray(), $privilegeIds);
//
//                $userRow = DepartmentUser::getCurrentInfo($orderInfo['uid'])->toArray();
//
//                foreach ($userList as $tmpUserRow) {
//                    $tmpUid = $tmpUserRow['user_id'];
//
//                    $orderProcessCourseObj = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessRow['id'], 'uid' => $tmpUid]);
//                    $tmpInsertRow = [
//                        'uid' => $tmpUid,
//                        'total_number' => 0,//自动分派，需完成数量默认为0
//                        'order_process_id' => $orderProcessRow['id'],
//                        'assign_id' => $userId,//派发人id
////                        'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
//                        'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 临时调整-跳过领材阶段
//                        'company_id' => $companyId,//企业Id
//                    ];
//                    $orderProcessCourseObj->fill($tmpInsertRow);
//                    $orderProcessCourseObj->save();
//                    $orderPorcessCourseId = $orderProcessCourseObj->id;
//
//                    //存入工单列表关联表
//                    OrderEngine::importProcessCourseOrder($orderProcessCourseObj->toArray());
//                }
//
//                //调整：无工序管理员订单，员工开工后再修改工序订单状态
////                //修改工序工单状态为2（已接单）
////                $orderProcessRow->status = 2;
////                $orderProcessRow->save();
//
//                //修改工单状态
//                $orderObj = Order::where(['id' => $orderId])->first();
//                if (!empty($orderObj->toArray())) {
//                    $orderObj->status = 1;
//                    $orderObj->save();
//
//                    //修改工单列表关联表数据状态
//                    $type = 1;
//                    $relateId = $orderObj->id;
//                    $status = 1;
//                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
//                } else {
//                    return [
//                        'code' => 1,
//                        'message' => '参数错误'
//                    ];
//                }
//            }

//            return [
//                'type' => 3,
//                'message' => '分派成功'
//            ];
        }
    }

    //主工单工单详情-新接口
    public function getManagerOrderDetailListNew(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id
        $input['customer_order_flag'] = isset($input['customer_order_flag']) ? $input['customer_order_flag'] : '';//纯查看界面

        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //工单基础信息字段，目前格式固定 -- 已调整为后台控制 20180131
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        $customerAddressArr = [];
        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            $rightLabelValue = $orderInfo[$row['field_name']];
            if ($row['field_type'] == 9) {//图片处理
                //如果有上传的图片地址，存入数组中
                continue;//另外处理
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                //continue;//另外处理
                $addressWhere = ['id' => $rightLabelValue];
//                $customerAddress = CustomerAddress::getInfo($addressWhere);
                $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();

                if ($customerAddress) {
                    $customerAddressArr = $customerAddress->toArray();
                }
                continue;
            }


            $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);

            $baseInfoList[] = [
                'leftLabelValue' => $leftLabelValue,
                'rightLabelValue' => $rightLabelValue
            ];
        }

        if (!empty($customerAddressArr)) {
            $baseInfoList[] = [
                'leftLabelValue' => '收货人',
                'rightLabelValue' => $customerAddressArr['consignee']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '联系手机',
                'rightLabelValue' => $customerAddressArr['phone']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '区县地址',
                'rightLabelValue' => $customerAddressArr['province_name'] . ' ' . $customerAddressArr['city_name'] . ' ' . $customerAddressArr['area_name']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '详细地址',
                'rightLabelValue' => $customerAddressArr['address']
            ];
        }

        $isAllowUpdate = 1;
        if ($input['customer_order_flag']) {
            $isAllowUpdate = 2;
        }

        $listAll[] = [
            'titleLabelValue' => '基本信息',
            'order_id' => $orderInfo['id'],//工单id
            'is_allow_update' => $isAllowUpdate,//是否允许修改 1-允许 2-不允许
            'process_type' => 'base',//类型 base-主工单信息  process-工序工单信息
            'list' => $baseInfoList
        ];

        //动态获取工序数据
        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息


            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first();
            if (!$orderProcessInfo) {
                dd(['order_id' => $orderInfo['id'], 'process_type' => $processId]);
            }


            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            //工序工单状态
            $orderPorcessStautsTitleList = [
                '1' => '待接单',
                '2' => '待派发',
                '3' => '进行中',
                '4' => '已完工',
                '101' => '待开工',
            ];

            $orderPorcessStautsTitle = $orderPorcessStautsTitleList[$orderProcessInfo['status']];

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    //显示每种材料
                    $materialIdList = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    foreach ($materialIdList as $materialId) {
                        if ($materialId) {
                            //获取材料信息（名称）
                            $materialObj = ProductEngine::getProductInfo($materialId);
                            $materialName = $materialId;
                            if ($materialObj) {
                                $materialName = $materialObj->product_name;
                            }

                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => $materialName,
                            ];
                        }
                    }
                    continue;
                }

                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);


                $list[] = [
                    'leftLabelValue' => $processFieldRow['title'],
                    'rightLabelValue' => $showTitle,
                ];
            }

            $isAllowUpdate = 1;//是否允许修改
            if ($orderProcessInfo['status'] == 3 || $orderProcessInfo['status'] == 4) {//开工中或者已完工不允许修改工单
                $isAllowUpdate = 2;
            }

            if ($input['customer_order_flag']) {
                $isAllowUpdate = 2;
            }

            //未派发的情况下显示 待派发
            if(!$orderProcessInfo['uid']){
                $orderPorcessStautsTitle = '待派发';
            }

            $listAll[] = [
                'titleLabelValue' => $processTitle . '(' . $orderPorcessStautsTitle . ')',
                'order_process_id' => $orderProcessInfo['id'],
                'is_allow_update' => $isAllowUpdate,
                'process_type' => 'process',//类型 base-主工单信息  process-工序工单信息
                'list' => $list
            ];
        }

        $returnApe = [
            'imageList' => $imageList,
            'listAll' => $listAll
        ];
        return $returnApe;
    }


    //员工确认开工-判断是否可以开工
    public function checkConfirmStart(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工工单id
        $inputType = isset($input['type']) ? $input['type'] : 0;
        $inputUserId = isset($input['user_id']) ? $input['user_id'] : 0;

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $input['order_process_id'] = $orderProcessCourseRow['order_process_id'];
        }

        $userId = Func::getHeaderValueByName('userid');
//        if($inputType==1 && $inputUserId>0)
//        {
//            $userId = $inputUserId;
//        }
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();


        //判断员工能否开工
        $orderProcessId = $orderProcessInfo['id'];
        //获取前一步骤所有工艺
        $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preOrderProcessList) {
            $preOrderProcessList = $preOrderProcessList->toArray();
        } else {
            $preOrderProcessList = [];
        }

        //获取订单类型是否允许同时开工
        $orderTypeProcessId = OrderProcess::where('id', $orderProcessId)->first()->ordertype_process_id;
        $isMeanwhile = OrderType::isMeanwhileNextStep($orderTypeProcessId);

        $allowStart = 1;
        $message = '';
        if ($isMeanwhile) {
            //如果前面的工序已经开工则允许开工
            //前面的步骤待开工的数量（状态 1：待接单 2：待分派）
            $noStartProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noStartProcessNum != 0) {
                $allowStart = 0;
                $message = '请等待上道工序开工';
            }
        } else {
            //判断对应步骤的工艺是否都已经完成
            $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noCompleteProcessNum != 0) {
                $allowStart = 0;
                $message = '请等待上道工序完工';
            }
        }

        return [
            'code' => 0,
            'allow_start' => $allowStart,
            'message' => $message,
        ];
    }

    //主工单工单详情-新接口
    public function getOrderProductionCaseDiagram()
    {
        $orderId = request('order_id');
        if (!$orderId) {
            return [
                'code' => 1,
                'message' => '参数错误'
            ];
        }

        //获取主工单信息
        $orderInfo = Order::where(['id' => $orderId])->first();
        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        return [
            'imageList' => $imageList
        ];
    }


    //员工分批提交完成数量
    public function submitOrderProcessCourseGradation()
    {
        $orderProcessCourseId = request('order_process_course_id');
        $submitNum = request('submit_num');//完成数量
        $submitWasteNum = request('submit_waste_num');

        if (!$submitNum) {
            $submitNum = 0;
        }
        if (!$submitWasteNum) {
            $submitWasteNum = 0;
        }

        if ($submitNum && $submitWasteNum) {
            return [
                'code' => 1,
                'message' => '请填写数量',
            ];
        }

        //插入员工工单分批表
        $orderProcessCourseGradationObj = OrderProcessCourseGradation::firstOrNew(['id' => '']);
        $insertRow = [];
        $insertRow['order_process_course_id'] = $orderProcessCourseId;
        $insertRow['submit_num'] = $submitNum;
        $insertRow['submit_waste_num'] = $submitWasteNum;
        $insertRow['submit_time'] = time();
        $orderProcessCourseGradationObj->fill($insertRow);
        $orderProcessCourseGradationObj->save();

        //修改员工工单的
        $orderProcessCourseObj = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first();
        $orderProcessCourseObj->finish_number = $orderProcessCourseObj->finish_number + $submitNum;
        $orderProcessCourseObj->waste_number = $orderProcessCourseObj->waste_number + $submitWasteNum;
        $orderProcessCourseObj->save();

        return [
            'code' => 0,
            'message' => '提交成功',
        ];
    }

    //获取原始客户订单列表
    public function getOriginalCustomerOrderList()
    {

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $where = ['company_id' => $companyId];
        $originalCustomerOrderList = FlowCustomerOrder::where($where)->orderBy('id', 'desc')->get()->toArray();


        $tmpArr = [];
        foreach ($originalCustomerOrderList as $originalCustomerOrderRow) {
            $customerId = $originalCustomerOrderRow['customer_id'];//目前没有账户id对应客户id的功能
            $customerName = '';
            if ($customerId) {
                $customerName = CustomerEngine::getNameById($customerId);
            }

            $workplaceName = '';
            if ($originalCustomerOrderRow['workplace']) {
                $workplaceName = Buyers::getNameById($originalCustomerOrderRow['workplace']);
            }

            $originalCustomerOrderRow['customer_name'] = $customerName;
            $originalCustomerOrderRow['workplace_name'] = $workplaceName;

            $tmpArr[] = $originalCustomerOrderRow;
        }

        $originalCustomerOrderList = $tmpArr;

        return $originalCustomerOrderList;
    }

    //获取原始客户订单列表
    public function getOriginalCustomerOrderDetail()
    {

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $customerOrderId = request('customer_order_id');

        $where = ['id' => $customerOrderId];
        $originalCustomerOrderRow = FlowCustomerOrder::where($where)->first()->toArray();

        $customerId = 15;//目前没有账户id对应客户id的功能
        $customerName = CustomerEngine::getNameById($customerId);

        $originalCustomerOrderRow['customer_id'] = $customerId;
        $originalCustomerOrderRow['customer_name'] = $customerName;
        $originalCustomerOrderRow['workplace_name'] = Buyers::getNameById($originalCustomerOrderRow['workplace']);

        return $originalCustomerOrderRow;
    }

    //获取工单-版关联详情
    public function getOrderPlateDetail()
    {
        $orderPlateId = request('order_plate_id');
        $where = ['id' => $orderPlateId];
        $orderPlateRow = OrderPlate::where($where)->first()->toArray(0);

        $orderId = $orderPlateRow['order_id'];
        $orderProcessId = $orderPlateRow['order_process_id'];

        $showDate = date('Y-m-d', $orderPlateRow['created_at']);

        //技师
        $uid = OrderProcess::where(['id' => $orderProcessId])->first()->uid;
        if ($uid) {
            $userName = DepartmentUser::getCurrentInfo($uid)->truename;
        } else {
            $userName = '未分派';
        }

        //数量
        $orderInfo = Order::where(['id' => $orderId])->first()->toArray();
        $productNum = '';
        if ($orderInfo['product_num']) {
            $tmpProductNumArr = explode(',', $orderInfo['product_num']);
            if (isset($tmpProductNumArr[0])) {
                $productNum = $tmpProductNumArr[0];
            }
        }

        $content = unserialize($orderPlateRow['content']);

        //获取对应工单的材料信息
        //统计工序总共使用材料情况
        $orderProcessInfo = OrderProcess::where(['id'=>$orderProcessId])->first()->toArray();
        $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();

        $orderPorcessCourseIds = [];
        $finishNum = 0;//已完成数量
        foreach ($orderProcessCourseList as $orderProcessCourseRow) {
            $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
            $finishNum += $orderProcessCourseRow['finish_number'];
        }

        $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

        $orderMaterialListTmp = [];
        foreach ($orderMaterialArr as $orderMaterialRow) {
            if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
            } else {
                $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
            }
        }

        $orderMaterialList = [];
        foreach ($orderMaterialListTmp as $orderMaterialRow) {
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            //追加材料图片地址
            $materialRow['img_url'] = '';
            if($materialRow['img_id']){
                $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
            }

            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
            $where = ['product_id'=>$materialRow['id']];
            $productFields = $ProductFieldsModel->getData($where);

            $productFields = $productFields->map(function($item){
                $data['field_name'] = $item->field_name;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                $data['field_value'] = $item->$comumnName;
                return $data;
            });

            $materialRow['custom_fields'] = $productFields;


            $orderMaterialRow['info'] = $materialRow;
            $orderMaterialList[] = $orderMaterialRow;
        }

        $categoryIdMaterialList = [];
        foreach ($orderMaterialList as $materialRow){
            if(isset($categoryIdMaterialList[$materialRow['info']['category_id']])){
                $categoryIdMaterialList[$materialRow['info']['category_id']]['list'][] = $materialRow;
            }else{
                //获取分类名称
                $categoryName = \App\Eloquent\Ygt\Category::where(['id'=>$materialRow['info']['category_id']])->first()->cat_name;
                $categoryIdMaterialList[$materialRow['info']['category_id']]['categoryName'] = $categoryName;
                $categoryIdMaterialList[$materialRow['info']['category_id']]['categoryId'] = $materialRow['info']['category_id'];
                $categoryIdMaterialList[$materialRow['info']['category_id']]['list'][] = $materialRow;
            }
        }



        $machine = '';

        $detailList = [];
        foreach ($categoryIdMaterialList as $categoryId => $categoryIdMaterialRow){
            $categoryName = $categoryIdMaterialRow['categoryName'];
            $categoryId = $categoryIdMaterialRow['categoryId'];
            $detailRow = [
                'title' => $categoryName,
                'list' => [],
            ];
            foreach ($categoryIdMaterialRow['list'] as $materialRow){
                $desc = '';
                if($materialRow['receive_number']){
                    $desc .= "用量：".($materialRow['receive_number']-$materialRow['residual_number']-$materialRow['scrap_number'])."({$materialRow['info']['unit']})";
                }

                $detailRow['list'][] = [
                    'name' => $materialRow['info']['product_name'],
                    'imgUrl' => $materialRow['info']['img_url'],
                    'desc' => $desc,
                ];

            }
            $detailList[] = $detailRow;
        }


//        $orderPlateField = OrderEngine::getOrderPlateField();
//        $detailList = [];
//        foreach ($orderPlateField as $item => $filedRow) {
//            if ($item == 'machine') {
//                $machine = $content[$item];
//                continue;
//            }
//
//            $tmpListStr = $content[$item];
//            if ($tmpListStr) {
//                $tmpValueList = explode(',', $tmpListStr);
//                foreach ($tmpValueList as $tmpRow) {
//                    //判断是否是数字
//                    if (is_numeric($tmpRow)) {
//                        $collection = ProductEngine::getProductInfo($tmpRow);
//                        if ($collection) {//过滤异常情况
//                            $info = $collection->toArray();
//                            $tmpRow = $info['product_name'];
//                        }
//                    }
//
//                    $tmpList[] = [
//                        'name' => $tmpRow,
//                        'imgUrl' => '',
//                        'desc' => '',
//                    ];
//                }
//            } else {
//                $tmpList = [];
//            }
//
//            $detailList[] = [
//                'title' => $filedRow['title'],
//                'list' => $tmpList
//            ];
//        }

        $re = [
            'userName' => $userName,//技师
            'machine' => $machine,//机台
            'showDate' => $showDate,//展示日期
            'productNum' => $productNum,//数量
            'detailList' => $detailList,//用料详情
        ];
        return $re;
    }

    //通过客户id获取工厂列表
    public function getCompanyList()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();


        $companyList = [];
        $customerRow = Customer::where(['user_id' => $userId])->first();
        if ($customerRow) {
            $companyId = $customerRow->company_id;
            $companyName = Company::getOneValueById($companyId, 'title');
            $tmpArr = [
                'company_id' => $companyId,
                'company_name' => $companyName,
            ];
            $companyList[] = $tmpArr;
        }

        if (empty($companyList)) {
            //获取用户对应的厂
            $companyId = $userInfo['company_id'];
            $companyName = Company::getOneValueById($companyId, 'title');
            $tmpArr = [
                'company_id' => $companyId,
                'company_name' => $companyName,
            ];
            $companyList[] = $tmpArr;
        }


        return $companyList;
    }


    /**
     * Description:提交工单类型
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function customerOrderTypeSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        //校验参数
        $rules = [
            'order_type' => 'required',
        ];
        $message = [
            'order_type.required' => '未选择订单类型'
        ];
        $this->validateRequestParameters($input, $rules, true, $message);

        //是否归档
//        $isFile = request('is_file');


        //创建预生成订单&返回预生成订单id
        $customerOrderId = request('customer_order_id');
        $customerOrderPreRow = CustomerOrderPre::firstOrNew(['id' => $customerOrderId]);

        //订单号调整为正式生成订单时创建
//        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $orderTitle = '';

        //用户id&企业id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = OrderType::getOneValueById($input['order_type'], 'company_id');


        //获取userid对应的客户id
        $customerId = request('customer_id');
        if (!$customerId) {
            $customerId = OrderEngine::getCustomerIdByUid($userId);
        }

        $insertRow = [
            'order_type' => $input['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
            'is_trash' => 1,//默认设置为该记录为可删除
//            'is_file' => $isFile,//是否归档
            'customer_name' => $customerId,//客户id
        ];


        $customerOrderPreRow->fill($insertRow);
        $customerOrderPreRow->save();
        $orderId = $customerOrderPreRow->id;

        return ['order_id' => $orderId];
    }

    /**
     * Description:订单创建-基础信息-选项参数获取
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function customerOrderPreBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的订单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱订单id 测试数据

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $distributionOrderId = $input['order_id'];
        if ($pre_order_id !== '') {
            //草稿箱
            $curOrderRow = CustomerOrderPre::where(['id' => $pre_order_id])->first()->toArray();
            $orderId = $pre_order_id;
            $distributionOrderId = $orderId;
        } else if ($input['copy_order_id']) {
            //再来一单
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到订单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $curOrderRow = CustomerOrder::where(['id' => $input['copy_order_id']])->first()->toArray();
            //获取订单类型id
            $orderId = $input['order_id'];
            $distributionOrderId = $input['copy_order_id'];
        } else {
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到订单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $orderId = $input['order_id'];
        }

        //订单基础信息字段，目前格式固定
//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();


        $companyId = $curOrderRow['company_id'];
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        //添加默认值
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {
                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

                        $customerAddressRow = CustomerAddress::where(['id' => $customerAddressId])->first();
                        $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];

                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }

                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);
                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }

            }
        }

        $orderPreRow = CustomerOrderPre::where('id', $orderId)->first()->toArray();
        $orderType = $orderPreRow['order_type'];

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        return [
            'process_title' => '基础信息',
            'order_base_field_list' => $orderBaseFieldList,
            'button_title' => '下一步',
            'create_order_title' => '创建订单（1/' . ($processNum + 1) . '）'
        ];
    }

    /**
     * Description:订单创建-基础信息-提交
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function customerOrderPreBaseSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $companyId = $curOrderRow['company_id'];

        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $process_field_list = $orderBaseFieldList;
            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($process_field_list as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }


        //数据入库
        //创建预生成订单&返回预生成订单id
        $orderId = $input['order_id'];
        $orderPreRow = CustomerOrderPre::firstOrNew(['id' => $orderId]);
        $orderType = $orderPreRow->order_type;

        //修改数据
        foreach ($orderBaseFieldList as $fieldRow) {
            if (isset($input[$fieldRow['field_name']])) {
                $tmpFieldName = $fieldRow['field_name'];
                $orderPreRow->$tmpFieldName = $input[$fieldRow['field_name']];
            }
        }

        //限制交货日期
        if(isset($input['finished_date']) && $input['finished_date']){
            if(strtotime($input['finished_date']) < strtotime(date('Ymd')) ){
                return [
                    'code' => 1,
                    'message' => '交货日期不能早于今天'
                ];
            }
        }



        $orderPreRow->status = 1;//订单状态 1-待确认 2-待派单 3-待生产 4-生产中 5-已完工 6-已发货 7-已收讫
        $orderPreRow->is_trash = 0;//标记为不自动删除
        $orderPreRow->save();
        $orderPreRow->id;

        //返回该订单类型的第一个工序
        $orderTypeObj = new OrderType();
        $firstProcessRow = $orderTypeObj->getFirstStep($orderType);
        $firstProcessId = $firstProcessRow['process_id'];
        $firstOrdertypeProcessId = $firstProcessRow['id'];

        return [
            'process_id' => $firstProcessId,
            'ordertype_process_id' => $firstOrdertypeProcessId,
        ];
    }

    //工序信息获取统一接口
    public function getCustomerProcessDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//订单工序类型id
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//订单工序类型id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//订单id 测试数据1
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的订单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱订单id 测试数据

        $curOrderProcessRow = [];
        if ($pre_order_id) {
            $curOrderProcessRow = CustomerOrderProcessPre::where(['order_id' => $pre_order_id, 'process_type' => $input['process_id']])->first();
            if ($curOrderProcessRow) {
                $curOrderProcessRow = $curOrderProcessRow->toArray();
            }
            $input['order_id'] = $pre_order_id;
        } elseif ($input['copy_order_id']) {//如果传入复制订单id
            $customerOrderProcessObj = CustomerOrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first();
            if ($customerOrderProcessObj) {
                $curOrderProcessRow = $customerOrderProcessObj->toArray();
            } else {
                $curOrderProcessRow = [];
            }
        }


        //获取订单信息
        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        //通过工序id，获取对应的字段
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);

        //获取工序信息
        $processTitle = Process::getOneValueById($input['process_id'], 'title');

        //是否为工艺上最后一个工序
        $orderTypeObj = new OrderType();
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        }


        $buttonTitle = '';
        $isToCreate = 0;
        if ($nextProcessId) {
            $buttonTitle = '下一步';//按钮显示文字
        } else {
            $buttonTitle = '确认提交';//按钮显示文字
            $isToCreate = 1;
        }

        //获取工艺数目
        $curProcessNum = OrderType::getOrderTypeProcessNumber($orderType, $input['process_id']);
        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        //添加默认值
        if (!empty($curOrderProcessRow)) {
            foreach ($processFieldList as $key => $row) {
                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);

                        $materialList = [];
                        foreach ($materialIdList as $materialId) {
                            $materiaRow = ProductEngine::getProductInfo($materialId);
                            if ($materiaRow) {//过滤异常情况
                                $materiaRow->toArray();
                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materiaRow['product_no'],
                                    'product_name' => $materiaRow['product_name'],
                                ];
                            }
                        }
                        $processFieldList[$key]['default_product_list'] = $materialList;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }

                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }
                }
            }
        }

        //追加再基础信息中填写的客户id
        $customerId = '';
        if (isset($orderInfo['customer_name']) && $orderInfo['customer_name'] && $orderInfo['customer_name'] != '(null)') {
            $customerId = $orderInfo['customer_name'];
        }

        $return = [];
        $return['customer_id'] = $customerId;//基础信息的工序id
        $return['process_title'] = $processTitle;//工序名称
        $return['process_field_list'] = $processFieldList;//工序字段
        $return['button_title'] = $buttonTitle;//按钮显示文字
        $return['is_to_create'] = $isToCreate;//最后一步工序（需要展示归档还是创建订单）
        $return['create_order_title'] = '创建订单（' . ($curProcessNum + 1) . '/' . ($processNum + 1) . '）';//按钮显示文字

        return $return;
    }

    //工序提交统一接口
    public function customerProcessSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//订单工序类型
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//订单工序类型关联id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//订单-id
        $input['is_file'] = isset($input['is_file']) ? $input['is_file'] : 0;//是否归档
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据


        //判断是否是归档 || 存放是否归档状态
//        if ($input['is_file']) {
            //订单归档信息
            $customerOrderPreObj = CustomerOrderPre::where(['id' => $input['order_id']])->first();
            $customerOrderPreObj->is_file = $input['is_file'];
            $customerOrderPreObj->save();
//        }


        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $processFieldList = Process::getFieldListByProcessId($input['process_id']);
            //如果是第一个工序，添加字段‘需完成数量’--功能调整取消这一段

            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($processFieldList as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }

        //获取用户id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $companyId = $curOrderRow['company_id'];

        //获取工序所包含的字段
        $processFieldList = Process::getFieldArrByProcessId($input['process_id']);

        //数据入库
        //存入印刷工序提交的数据
        $orderProcessPreRow = CustomerOrderProcessPre::firstOrNew(['order_id' => $input['order_id'], 'process_type' => $input['process_id']]);

        $insertRow = [
            'order_id' => $input['order_id'],//关联的订单id
            'process_type' => $input['process_id'],//工序类型
            'ordertype_process_id' => $input['ordertype_process_id'],//工序订单类型关联id
            'company_id' => $companyId,
        ];


        //如果是第一道工序，添加字段需完成数量--功能调整,第一个工序需完成数量取产品的数量
        //调整为所有工序需完成数量都由订单产品数量挂钩

        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first();
        //获取订单基础信息设置的数量
        $tmpArr = explode(',', $orderInfo['product_num']);
        $productNum = $tmpArr[0];
        if (!$productNum || !is_numeric($productNum)) {
            $productNum = 0;
        }
        $insertRow['completed_number'] = $productNum;

        foreach ($processFieldList as $processField) {
            $insertRow[$processField] = $input[$processField];
        }

        $orderProcessPreRow->fill($insertRow);
        $orderProcessPreRow->save();

        //如果是最后一道工序，订单创建完成
        //获取订单信息
        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        $orderTypeObj = new OrderType();
        $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
            $nextOrdertypeProcessId = $nextOrderTypeProcessRow[0]['id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
            $nextOrdertypeProcessId = '';
        }

        if ($nextProcessId || $input['is_draft']) {//有下一步或者是退出保存操作
            if ($nextProcessId) {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                    'next_process_id' => $nextProcessId,//下一道工序的id
                    'next_ordertype_process_id' => $nextOrdertypeProcessId,//下一道工序的工序订单类型关联id
                ];
            } else {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                ];
            }
            return $return;
        } else {//提交生成正式订单
            $orderId = $this->customerOrderCreate($input['order_id']);
            $return = [
                'is_final' => 1,//是否为最后一道工序
                'message' => '创建成功',//提示信息
                'order_id' => $orderId,//创建成功的订单id
                'order_type' => $orderType,//创建成功的订单工序类型
            ];
            return $return;
        }
    }

    /**
     * Description:正式生成订单数据
     * User: zhuyujun
     * @param $orderPreId
     */
    public function customerOrderCreate($orderPreId)
    {
        $orderId = '';
        //基础信息
        //取出预生成数据
        $orderPre = CustomerOrderPre::where('id', $orderPreId);
        $orderPreRow = $orderPre->first()->toArray();

        //获取登陆用户信息
        $userId = $orderPreRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $orderPreRow['company_id'];

        //存入正式数据
        $order = CustomerOrder::firstOrNew(['id' => '']);
        unset($orderPreRow['id']);//不使用预生成表的id
        unset($orderPreRow['is_trash']);//删除草稿箱表独有的字段
        $orderPreRow['order_pre_id'] = $orderPreId;//存入对应的草稿箱

        ////生成订单号
        //获取该订单是当天的第几单
        $dayStartTime = strtotime(date('Ymd'));
        $intradayOrderCount = CustomerOrder::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

        $ordeTitleIndex = '';
        $intradayOrderCount++;
        if ($intradayOrderCount < 10) {
            $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
        } else {
            $ordeTitleIndex = $intradayOrderCount;
        }
        $orderPreRow['order_title'] = 'DD' . date('ymd') . $ordeTitleIndex;

        $order->fill($orderPreRow);
        $order->save();
        $orderId = $order->id;
        $foreignKey = $order->id;
        //删除预生成数据
        //基础信息
        $orderPre->delete();

        //数据加入到订单列表关联表中
        $orderPreRow['id'] = $orderId;
//        OrderEngine::importMainOrder($orderPreRow);


        //工序信息处理
        $orderProcessPreList = CustomerOrderProcessPre::where('order_id', $orderPreId)->get();

        //获取第一道步骤涉及的工序
        $processFirstList = OrderType::getFirstProcessBag($orderPreRow['order_type'])->toArray();

        foreach ($orderProcessPreList as $orderProcessPreObj) {
            $orderProcessPreRow = $orderProcessPreObj->toArray();
            //存入正式数据
            $orderProcess = CustomerOrderProcess::firstOrNew(['id' => '']);
            $orderProcessPreRow['order_id'] = $orderId;
            $orderProcessPreRow['status'] = 1;//订单工序默认状态为，1-待接单 2-确认开工（未领取材料） 3-已领取材料 4-确认完工
            $orderProcess->fill($orderProcessPreRow);
            $orderProcess->save();
            ////添加材料
            //获取字段信息
            $orderProcessPreObj->delete();
        }

        //如果是归档，不需要发送消息
        $isFile = $orderPreRow['is_file'];

        if (!$isFile) {
            //发送消息给下单人
            //获取下单人权限列表
            $appnodeId = 1;//有下单功能
            $privilegeList = Privilege::getPrivilegeIds($companyId, $appnodeId);

            foreach ($privilegeList as $privilegeId) {
                //发送消息给下单人
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 16,
                    'type_id' => $orderId,
                    'title' => '客户订单',
                    'content' => '有新的订单'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }


        //添加开票表客户订单id
        $customerOrderBillingObj = CustomerOrderBilling::where(['customer_order_pre_id' => $orderPreRow['order_pre_id']])->first();
        if ($customerOrderBillingObj) {
            $customerOrderBillingObj->customer_order_id = $orderId;
            $customerOrderBillingObj->save();
        }


        return $orderId;
    }

    //订单详情
    public function getCustomerOrderDetail()
    {
        //获取传入数据
        $customerOrderId = request('customer_order_id');
        $input['order_id'] = $customerOrderId;//订单-id

        //获取订单信息
        $orderInfo = CustomerOrder::where('id', $input['order_id'])->first()->toArray();

        //订单基础信息字段，目前格式固定 -- 已调整为后台控制 20180131
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $orderInfo['company_id'];
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        $customerAddressArr = [];
        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            $rightLabelValue = $orderInfo[$row['field_name']];
            if ($row['field_type'] == 9) {//图片处理
                //如果有上传的图片地址，存入数组中
                continue;//另外处理
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                //continue;//另外处理
                $addressWhere = ['id' => $rightLabelValue];
//                $customerAddress = CustomerAddress::getInfo($addressWhere);
                $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                if ($customerAddress) {
                    $customerAddressArr = $customerAddress->toArray();
                }
                continue;
            }


            $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);

            $baseInfoList[] = [
                'leftLabelValue' => $leftLabelValue,
                'rightLabelValue' => $rightLabelValue
            ];
        }
        if (!empty($customerAddressArr)) {
            $baseInfoList[] = [
                'leftLabelValue' => '收货人',
                'rightLabelValue' => $customerAddressArr['consignee']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '联系手机',
                'rightLabelValue' => $customerAddressArr['phone']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '区县地址',
                'rightLabelValue' => $customerAddressArr['province_name'] . ' ' . $customerAddressArr['city_name'] . ' ' . $customerAddressArr['area_name']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '详细地址',
                'rightLabelValue' => $customerAddressArr['address']
            ];
        }

        $listAll[] = [
            'titleLabelValue' => '基本信息',
            'list' => $baseInfoList,
            'listImageList' => [],
        ];

        //动态获取工序数据
        //获取订单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息
            $orderProcessInfo = CustomerOrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first();

            $orderProcessInfo = CustomerOrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    //显示每种材料
                    $materialIdList = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    foreach ($materialIdList as $materialId) {
                        if ($materialId) {
                            //获取材料信息（名称）
                            $materialObj = ProductEngine::getProductInfo($materialId);
                            $materialName = $materialId;
                            if ($materialObj) {
                                $materialName = $materialObj->product_name;
                            }

                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => $materialName,
                            ];
                        }
                    }
                    continue;
                }

                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);


                $list[] = [
                    'leftLabelValue' => $processFieldRow['title'],
                    'rightLabelValue' => $showTitle,
                ];
            }

            $listAll[] = [
                'titleLabelValue' => $processTitle,
                'list' => $list,
                'listImageList' => [],
            ];
        }

        //增加开票信息
        $customerOrderBillingRow = CustomerOrderBilling::where(['customer_order_id' => $customerOrderId])->first();
        if ($customerOrderBillingRow) {
            //附件图片
            $listImageList = [];
            if ($customerOrderBillingRow['img']) {
                $tmpImgIdList = explode(',', $customerOrderBillingRow['img']);
                foreach ($tmpImgIdList as $tmpImgId) {
                    if ($tmpImgId) {
                        $imageUrl = ImgUpload::getImgUrlById($tmpImgId, true, false);
                        $listImageList[] = $imageUrl;
                    }
                }
            }


            //增加开票资料信息
            $list1 = [];
            if(isset($customerOrderBillingRow['invoice_id']) && $customerOrderBillingRow['invoice_id']){
                $invoiceId = $customerOrderBillingRow['invoice_id'];
                $customerInvoiceRow = CustomerInvoice::where(['id'=>$invoiceId])->first()->toArray();
                $list1 = [
                    [
                        'leftLabelValue' => '账户名称',
                        'rightLabelValue' => $customerInvoiceRow['account_name'],
                    ],
                    [
                        'leftLabelValue' => '纳税人识别号',
                        'rightLabelValue' => $customerInvoiceRow['taxpayer_number'],
                    ],
                    [
                        'leftLabelValue' => '省市区',
                        'rightLabelValue' => $customerInvoiceRow['province_name'].$customerInvoiceRow['city_name'].$customerInvoiceRow['area_name'],
                    ],
                    [
                        'leftLabelValue' => '详细地址',
                        'rightLabelValue' => $customerInvoiceRow['address'],
                    ],
                    [
                        'leftLabelValue' => '电话',
                        'rightLabelValue' => $customerInvoiceRow['telphone'],
                    ],
                    [
                        'leftLabelValue' => '开户行',
                        'rightLabelValue' => $customerInvoiceRow['opening_bank'],
                    ],
                    [
                        'leftLabelValue' => '银行卡号',
                        'rightLabelValue' => $customerInvoiceRow['bank_card_number'],
                    ],
                ];

            }

            $list2 = [
                [
                    'leftLabelValue' => '金额',
                    'rightLabelValue' => $customerOrderBillingRow['money'],
                ],
                [
                    'leftLabelValue' => '开户银行',
                    'rightLabelValue' => $customerOrderBillingRow['bank'],
                ],
                [
                    'leftLabelValue' => '支付方式',
                    'rightLabelValue' => $customerOrderBillingRow['pay_type'],
                ],
                [
                    'leftLabelValue' => '收款日期',
                    'rightLabelValue' => $customerOrderBillingRow['collection_days'],
                ],
            ];

            $list = array_merge($list1,$list2);


            $listAll[] = [
                'titleLabelValue' => '开票信息',
                'list' => $list,
                'listImageList' => $listImageList,
            ];
        }

        $allowCustomerOrderToOrder = 0; //是否允许创建工单 1-允许 0-不允许
        //判断是否有权限订单转订单
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        if ($isManager) {
            $allowCustomerOrderToOrder = 1;

            //如果订单已经转过工单，不允许再创建工单
            $orderCount = Order::where(['customer_order_id' => $customerOrderId])->count();
            if ($orderCount) {
                $allowCustomerOrderToOrder = 0;
            } else {
                $allowCustomerOrderToOrder = 1;
            }

            //如果订单归档，不能创建工单
            if($orderInfo['is_file']){
                $allowCustomerOrderToOrder = 0;
            }
        }


        $returnApe = [
            'allowCustomerOrderToOrder' => $allowCustomerOrderToOrder,
            'customer_order_id' => $customerOrderId,
            'imageList' => $imageList,
            'listAll' => $listAll,
        ];

        return $returnApe;
    }

    //订单转订单
    public function customerOrderToOrder()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $customerOrderId = request('customer_order_id');

        //订单基础信息导入到订单表（草稿箱）中
        $customerOrderRow = CustomerOrder::where(['id' => $customerOrderId])->first()->toArray();

        $orderPreObj = OrderPre::firstOrNew(['id' => '']);

        //过滤不需要的字段
        unset($customerOrderRow['is_file']);
        unset($customerOrderRow['order_pre_id']);
        unset($customerOrderRow['is_deal_price']);

        //字段调整
        $customerOrderRow['uid'] = $userId;
        $customerOrderRow['customer_order_id'] = $customerOrderId;

        $orderPreObj->fill($customerOrderRow);
        $orderPreObj->save();
        $orderId = $orderPreObj->id;

        //订单工序信息导入到订单表（草稿箱）中
        $customerOrderProcessList = CustomerOrderProcess::where(['order_id' => $customerOrderId])->get()->toArray();
        foreach ($customerOrderProcessList as $tmpCustomerOrderProcessRow) {
            //字段调整
            unset($tmpCustomerOrderProcessRow['id']);
            $tmpCustomerOrderProcessRow['order_id'] = $orderId;

            $orderProcessPreObj = OrderProcessPre::firstOrNew(['id' => '']);
            $orderProcessPreObj->fill($tmpCustomerOrderProcessRow);
            $orderProcessPreObj->save();
        }

        return ['order_id' => $orderId];
    }


    //订单开票
    public function customerOrderBillingInfo()
    {
        $payTypeList = [
            [
                'id' => 1,
                'name' => '现金',
            ],
            [
                'id' => 2,
                'name' => '汇款',
            ],
            [
                'id' => 3,
                'name' => '承兑汇票',
            ]
        ];

        $re = [
            'payTypeList' => $payTypeList,
        ];

        return $re;
    }


    //订单开票-数据提交
    public function customerOrderBillingSubmit()
    {
        $money = request('money') ? request('money') : 0; //金额
        $bank = request('bank'); //开户银行
        $bank_number = request('bank_number'); //银行账号
        $pay_type = request('pay_type'); //支付方式
        $collection_days = request('collection_days');//收款日期
        $customerOrderId = request('order_id');//收款日期
        $img = request('img'); //附件图片，图片id
        $invoiceId = request('invoice_id'); //关联的开票资料id

        if(!$invoiceId){
            return [
                'code' => 1,
                'message' => '请选择开票资料'
            ];
        }


        //生成一个新的客户订单id -- 不是再来一单的情况下
        if (!$customerOrderId) {
            $customerOrderObj = CustomerOrderPre::firstOrNew(['id' => '']);
            $customerOrderObj->save();
            $customerOrderId = $customerOrderObj->id;
        }

        $customerOrderBillingObj = CustomerOrderBilling::firstOrNew(['id' => $customerOrderId]);
        $insertRow = [
            'customer_order_pre_id' => $customerOrderId,
            'money' => $money,
            'bank' => $bank,
            'bank_number' => $bank_number,
            'pay_type' => $pay_type,
            'collection_days' => $collection_days,
            'img' => $img,
            'invoice_id' => $invoiceId,
        ];
        $customerOrderBillingObj->fill($insertRow);
        $customerOrderBillingObj->save();

        $re = [
            'customer_order_id' => $customerOrderId,//客户订单id
        ];

        return $re;
    }

    //订单再来一单，获取开票消息等基础信息
    public function copyCustomerOrderFirst()
    {
        $copyOrderId = request('copy_order_id'); //复制订单id

        //旧工单消息
        $copyCustomerOrderRow = CustomerOrder::where(['id' => $copyOrderId])->first();
        if ($copyCustomerOrderRow) {
            $copyCustomerOrderRow = $copyCustomerOrderRow->toArray();
        } else {
            $copyCustomerOrderRow = '';
        }

        $companyId = '';//默认选择的工厂id
        $companyName = '';//默认选择的工厂名称
        $needBilling = 0;//是否开票 0-不开票，1-开票
        $money = '';//金额
        $bank = '';//开户银行
        $bankNumber = '';//银行账号
        $payType = '';//支付方式
        $collectionDays = '';//收款日期
        $imgId = '';//图片id
        $imgUrl = '';//图片地址
        $invoiceId = '';//关联的开票资料id
        $invoiceName = '';

        if ($copyCustomerOrderRow) {
            //默认厂id,名称
            $companyId = $copyCustomerOrderRow['company_id'];
            $companyName = Company::getOneValueById($companyId, 'title');

            //默认是否开票
            //默认开票信息
            $customerOrderBillingRow = CustomerOrderBilling::where(['customer_order_id' => $copyOrderId])->first();
            if ($customerOrderBillingRow) {
                $needBilling = 1;
                $customerOrderBillingRow = $customerOrderBillingRow->toArray();
                $money = $customerOrderBillingRow['money'];
                $bank = $customerOrderBillingRow['bank'];
                $bankNumber = $customerOrderBillingRow['bank_number'];
                $payType = $customerOrderBillingRow['pay_type'];
                $collectionDays = $customerOrderBillingRow['collection_days'];

                $imgId = $customerOrderBillingRow['img'];
                if ($imgId) {
                    $imgIdArr = explode(',', $imgId);
                    foreach ($imgIdArr as $tmpImgId) {
                        if (!trim($tmpImgId)) {//过滤空格 图片id应该不会有0
                            continue;
                        }
                        $tmpImgUrl = ImgUpload::getImgUrlById($tmpImgId);
                        $imgUrl .= $tmpImgUrl . ',';
                    }

                    $imgUrl = trim($imgUrl, ',');
                }

                $invoiceId = $customerOrderBillingRow['invoice_id'];
                $customerInvoiceObj = CustomerInvoice::where(['id'=>$invoiceId])->first();
                if($customerInvoiceObj){
                    $invoiceName = $customerInvoiceObj->account_name;
                }

            }

            //创建预生成订单&返回预生成订单id
            $customerOrderPreRow = CustomerOrderPre::firstOrNew(['id' => '']);

            $orderType = $copyCustomerOrderRow['order_type'];
            $userId = $copyCustomerOrderRow['uid'];
            $customerId = $copyCustomerOrderRow['customer_name'];

            $companyId = OrderType::getOneValueById($orderType, 'company_id');
            $insertRow = [
                'order_type' => $orderType,
                'order_title' => '',
                'uid' => $userId,
                'company_id' => $companyId,
                'is_trash' => 1,//默认设置为该记录为可删除
//            'is_file' => $isFile,//是否归档
                'customer_name' => $customerId,//客户id
            ];
            $customerOrderPreRow->fill($insertRow);
            $customerOrderPreRow->save();
            $orderId = $customerOrderPreRow->id;
        } else {
            return [
                'code' => 1,
                'message' => '参数出错了'
            ];
        }

        $re = [
            'company_id' => $companyId,
            'company_name' => $companyName,
            'need_billing' => $needBilling,
            'money' => $money,
            'bank' => $bank,
            'bank_number' => $bankNumber,
            'pay_type' => $payType,
            'collection_days' => $collectionDays,
            'img_id' => $imgId,
            'img_url' => $imgUrl,
            'invoice_id' => $invoiceId,
            'invoice_name' => $invoiceName,
            'order_id' => $orderId,
            'customer_id' => $customerId,//新增，返回客户id
        ];

        return $re;
    }

    //创建订单第一步，提供默认值
    public function createCustomerOrderFirst()
    {
        $customerId = request('customer_id'); //客户id

        $customerObj = Customer::where(['id'=>$customerId])->first();
        if($customerObj){
            $companyId = $customerObj->company_id;
            $companyName = Company::getOneValueById($companyId, 'title');
        }else{
            $companyId = '';//默认选择的工厂id
            $companyName = '';//默认选择的工厂名称
        }
        $re = [
            'company_id' => $companyId,
            'company_name' => $companyName,
            ];

        return $re;
    }

    //管理员工单详情
    public function getManagerOrderDetailNew(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id


        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';


        $list = [];//对应页面上横向列表
        $list[] = [
            'statusValue' => '',
            'departmentValue' => '待处理',
            'leftHiden' => 1,
            'rightHiden' => 0,
            'statusHiden' => 1,
            'departmentFontColor' => $blueColor,
            'statusViewBG' => $blueColor,
            'statusViewBorderColor' => $blueColor,
            'androidBg' => $androidBgBlue
        ];//默认自带条目

        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];

        $manageOrderProcessList = [];//工序工单信息
        foreach ($orderProcessList as $processId) {
            if (!$orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
                continue;
            }

            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();


            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;


            //已完成状态可以查看
            $lookDetaileButtonHiden = 0;
            $buttontitle = '查看';
            $seeDetaileFunctionName = 'seeDetaileAction';

            ////判断下一个工序是否需要工序管理员分派
            ////如果该工序没有设置工序管理员&未分派
            $privilegeAssignmentIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderInfo['order_type'], $processId, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
            if ($orderProcessInfo['uid']) {
                $userInfo = DepartmentUser::getCurrentInfo($orderProcessInfo['uid'])->toArray();
                $showUserName = $userInfo['truename'];
            } else {
                $showUserName = '';
            }

            if (!$privilegeAssignmentIds->count()) {//工序没有设置工序管理员
                //工单操作改为员工

                //没有配置工序管理员&员工还未分派工单
                $orderProcessCourse = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                if (!$orderProcessCourse->count()) {//表示未分派
                    $buttontitle = '分派';
                    $seeDetaileFunctionName = 'goSendAction';
                    $showUserName = '无';
                } else {
                    $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourse->first()->uid)->toArray();
                    $showUserName = $userInfo['truename'];
                    if ($orderProcessCourse->count() > 1) {
                        $showUserName .= '等';
                    }
                }
            }

            if ($orderProcessInfo['status']) {//待接单状态不显示 调整--待接单状态也显示 20180305 18:30

                //调整-预计完成时间调整为从员工工单获取
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                $finishNum = 0;

                $processId = $orderProcessInfo['process_type'];
                $where = ['id' => $processId];
                $process = Process::withTrashed()->where($where)->first()->toArray();

                $processIsSum = $process['is_sum'];//工序数量是否累加0不累加1累加

                $finishUserNumList = [];
                $minStatrTime = 0;
                $maxEndTime = 0;
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                    //设定的角色不进行统计数量到工序数量中
                    //过滤异常数据
                    if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                        continue;
                    }

                    if(!$minStatrTime || $orderProcessCourseRow['start_time'] < $minStatrTime){
                        $minStatrTime = $orderProcessCourseRow['start_time'];
                    }

                    $tmpEndTime = $orderProcessCourseRow['start_time'] + (int)($orderProcessCourseRow['estimated_time_minute']*60);
                    if(!$maxEndTime || $tmpEndTime > $maxEndTime){
                        $maxEndTime = $tmpEndTime;
                    }

                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                        continue;
                    }

                    $finishNum += $orderProcessCourseRow['finish_number'];
                    if (!$processIsSum) {//不累加
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];

                        if (isset($finishUserNumList[$tmpPrivilegeId])) {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                        } else {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                        }
                    }
                }

                //不累加--未完工时取完成量最小的员工
                if (!empty($finishUserNumList)) {
                    $finishMinNum = '';
                    foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                        if ($finishMinNum === 0) {//如果有员工完成数量为0，
                            break;
                        }

                        if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                            $finishMinNum = $finishUserNumRow['finish_number'];
                        }
                    }
                    $finishNum = $finishMinNum;
                }

                //统计工序总共使用材料情况
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
                $orderPorcessCourseIds = [];
                $finishNum = 0;//已完成数量
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                    $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                    $finishNum += $orderProcessCourseRow['finish_number'];
                }

                $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

                $orderMaterialListTmp = [];
                foreach ($orderMaterialArr as $orderMaterialRow) {
                    if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['retreat_number'] += $orderMaterialRow['retreat_number'];
                    } else {
                        $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                    }
                }

                $orderMaterialList = [];
                foreach ($orderMaterialListTmp as $orderMaterialRow) {
//                    $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
                    $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);
                    if(!$materialRow){
                        $materialRow = ProductEngine::getProductInfoTrash($orderMaterialRow['material_id']);
                        $materialRow['product_name'] = $materialRow['product_name']."[已删除]";
                    }

                    //追加材料图片地址
                    $materialRow['img_url'] = '';
                    if($materialRow['img_id']){
                        $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
                    }

                    //追加材料自定义属性
                    $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                    $where = ['product_id'=>$materialRow['id']];
                    $productFields = $ProductFieldsModel->getData($where);

                    $productFields = $productFields->map(function($item){
                        $data['field_name'] = $item->field_name;
                        $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                        $data['field_value'] = $item->$comumnName;
                        return $data;
                    });

                    $materialRow['custom_fields'] = $productFields;


                    $orderMaterialRow['info'] = $materialRow;
                    $orderMaterialList[] = $orderMaterialRow;
                }

                //统计工序开始时间&完工时间（预计） （开始时间取最早的员工开工时间，预计完工时间取最晚的完工时间）
                $orderProcessStartTime = $orderProcessEndTime = $orderProcessCostTime = '';
                if($minStatrTime){
                    $orderProcessStartTime = date('m-d H:i',$minStatrTime);
                }
                if($maxEndTime){
                    $orderProcessEndTime = date('m-d H:i',$maxEndTime);
                }

                if($minStatrTime && $maxEndTime){
                    $orderProcessCostTime = ((int)(($maxEndTime-$minStatrTime)/3600 * 10))/10;//计算耗时，过滤浮点数很多小数位问题
                    $orderProcessCostTime .= '小时';
                }


                //工序管理员名称
                $orderProcessManagerUid = $orderProcessInfo['uid'];
                $orderProcessManagerName = DepartmentUser::getCurrentInfo($orderProcessManagerUid)->truename;

                $manageOrderProcessList[] = [
                    'orderProcessId' => $orderProcessInfo['id'],//工序工单id
                    'orderProcessManagerName' => $orderProcessManagerName,//工序管理员名称
                    'processTitle' => $processTitle,//工序名称
                    'orderProcessStatus' => $statusArray[$orderProcessInfo['status']],//工序工单状态
                    'finishNum' => $finishNum,//工序完成数量（页面上没有，但我觉得肯定会用到，先预留着）
                    'orderMaterialList' => $orderMaterialList,//工序工单材料列表
                    'orderProcessStartTime' => $orderProcessStartTime,//工序开始时间
                    'orderProcessEndTime' => $orderProcessEndTime,//工序开始时间
                    'orderProcessCostTime' => $orderProcessCostTime,//工序耗时
                ];

            }


//            if($orderProcessInfo['status'] == 2 || $orderProcessInfo['status'] == 3){
            if (isset($orderProcessInfo['status']) && $orderProcessInfo['status'] && $orderProcessInfo['status'] != 1 && $orderProcessInfo['status'] != 101 && $orderProcessInfo['status'] != 2) {
                $statusValue = $statusArray[$orderProcessInfo['status']];
                $useColor = $blueColor;
                $androidBg = $androidBgBlue;
                $statusHiden = 0;
                $leftHiden = 0;
                $rightHiden = 0;
            } else {
                $statusValue = '';
                $useColor = $greColor;
                $androidBg = $androidBgGrey;
                $statusHiden = 1;
                $leftHiden = 0;
                $rightHiden = 0;
            }


            $list[] = [
                'statusValue' => $statusValue,//'生产中'
                'departmentValue' => $processTitle,//'彩印部门'
                'leftHiden' => $leftHiden,
                'rightHiden' => $rightHiden,
                'statusHiden' => $statusHiden,
                'departmentFontColor' => $useColor,
                'statusViewBG' => $useColor,
                'statusViewBorderColor' => $useColor,
                'androidBg' => $androidBg
            ];
        }

        if ($orderInfo['status'] == 3) {//已经完成
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $blueColor;
            $androidBg = $androidBgBlue;
            $statusHiden = 0;
            $leftHiden = 0;
            $rightHiden = 1;
        } else {
            $statusValue = '';
            $processTitle = '已完成';
            $useColor = $greColor;
            $androidBg = $androidBgGrey;
            $statusHiden = 1;
            $leftHiden = 0;
            $rightHiden = 1;
        }
        $list[] = [
            'statusValue' => $statusValue,//'生产中'
            'departmentValue' => $processTitle,//'彩印部门'
            'leftHiden' => $leftHiden,
            'rightHiden' => $rightHiden,
            'statusHiden' => $statusHiden,
            'departmentFontColor' => $useColor,
            'statusViewBG' => $useColor,
            'statusViewBorderColor' => $useColor,
            'androidBg' => $androidBg
        ];

        //获取工序对应的详细信息
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $returnApe = [
            'productImage' => $exampleImg,
            'productNameValue' => $orderTypeTitle,
            'productOrderValue' => '生产单号:' . $orderInfo['order_title'],
            'orderId' => $orderInfo['id'],
            'list' => $list,
            'manageOrderProcessList' => $manageOrderProcessList,
        ];
        return $returnApe;
    }

    public function getProcessManagerOrderDetailNew()
    {
        $orderProcessId = request('order_process_id');
        $order_process_info = OrderProcess::where('id', $orderProcessId)->first();

        $processTitle = Process::getOneValueById($order_process_info['process_type'], 'title');

        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];
        $processStatusStr = $statusArray[$order_process_info['status']];
        $processInfoStr = $processStatusStr . '[' . $processTitle . ']';

        $orderinfo = $this->info($order_process_info->order_id);

        ////替换产品名称为工序类型名称
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderinfo['order_type'], 'title');
        $orderinfo['product_name'] = $orderTypeTitle;

        $list = OrderProcessCourse::getAllWithUser($orderProcessId, $order_process_info['company_id']);

        //增加限制
        $userId = Func::getHeaderValueByName('userid');
        foreach ($list as &$row) {
            $row['is_allow_write'] = 0;
            if ($userId == $order_process_info['uid']) {//允许
                $row['is_allow_write'] = 1;
            }
        }


        $courseStatusArray = [
            '1' => '待开工',
            '2' => '待领取材料',
            '3' => '生产中',
            '4' => '已完成',
        ];
        $list->transform(function ($item) use ($courseStatusArray) {
            $item->statusStr = $courseStatusArray[$item->status];
            $item->creat_time = $item->created_at->formatLocalized('%Y-%m-%d');
            if (!$item->waste_number) {
                $item->waste_number = 0;
            }
            return $item;
        });


        //统计工序完成数量
        $processIsSum = Process::getOneValueById($order_process_info['process_type'], 'is_sum');

        $tmpUserList = [];
        $finishUserNumList = [];
        //员工分组，按角色分类
        $allMoney = 0;//总计件工资
        $finishNum = 0;//总完成数量
        $privilegeWageList = [];
        foreach ($list as $tmpRow) {
            $tmpUid = $tmpRow->uid;

            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');


            ////计价工资调整为管理员在工单里设置的值
            //先判断有没有批量设置角色计件工资
            $tmpOrderWage = '';
            $tmpOrderProcessId = $tmpRow['order_process_id'];
            $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_id'=>$tmpOrderProcessId,'privilege_id'=>$tmpPrivilegeId])->first();
            if($tmpOrderWageObj){
                $tmpOrderWage = $tmpOrderWageObj->piece_wage;
                if(!isset($privilegeWageList[$tmpPrivilegeId])){
                    $privilegeWageList[$tmpPrivilegeId] = $tmpOrderWage;
                }
            }

            //设置在个人上的计件工资优先级更高
            $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_course_id'=>$tmpRow['id']])->first();
            if($tmpOrderWageObj){
                $tmpOrderWage = $tmpOrderWageObj->piece_wage;
            }

            $tmpRow->price = $tmpOrderWage;
            $tmpRow->money = $tmpUserInfo['price'] * $tmpRow['finish_number'];

            //增加开工，完工（预计）时间，耗时
            $startTime = $endTimeStamp = $endTime = $costTime = '';
            if($tmpRow->start_time){
                $startTime = date('m-d H:i',$tmpRow->start_time);
            }

            if($tmpRow->start_time &&  $tmpRow->estimated_time_minute){
                $endTimeStamp = $tmpRow->start_time + (int)($tmpRow->estimated_time_minute*60);
                $endTime = date('m-d H:i',$endTimeStamp);
                $costTime = ((int)(($endTimeStamp-$tmpRow->start_time)/3600 * 10))/10;//计算耗时，过滤浮点数很多小数位问题
                $costTime .= '小时';
            }


            $tmpRow->startTime = $startTime;
            $tmpRow->endTime = $endTime;
            $tmpRow->costTime = $costTime;


            //最近操作日期
            $tmpRowArr = $tmpRow->toArray();
            $tmpRow->workDate = date('m-d H:i',$tmpRowArr['updated_at']);

            if (isset($tmpUserList[$tmpPrivilegeId])) {
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] += $tmpRow->finish_number;//同角色总数量
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] += $tmpRow->finish_number * $tmpRow->price;//同角色总计件工资
                $tmpUserList[$tmpPrivilegeId]['sumUserNum']++;//同角色总人数

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            } else {
                $tmpUserList[$tmpPrivilegeId]['privilegeId'] = $tmpPrivilegeId;
                $tmpUserList[$tmpPrivilegeId]['privilegeTitle'] = $tmpPrivilegeTitle;
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] = $tmpRow->finish_number;
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] = $tmpRow->finish_number * $tmpRow->price;
                $tmpUserList[$tmpPrivilegeId]['sumUserNum'] = 1;
                $tmpPrivilegePieceWage = isset($privilegeWageList[$tmpPrivilegeId]) ?  $privilegeWageList[$tmpPrivilegeId] : '';

                $tmpUserList[$tmpPrivilegeId]['privilege_piece_wage'] = $tmpPrivilegePieceWage;

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            }


            //设定的角色不进行统计数量到工序数量中
            //过滤异常数据
            if(!DepartmentUser::getCurrentInfo($tmpRow->uid)){
                continue;
            }
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpRow->uid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                continue;
            }


            $finishNum += $tmpRow->finish_number;

            if (!$processIsSum) {//不累加
                if (isset($finishUserNumList[$tmpPrivilegeId])) {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $tmpRow['finish_number'];
                } else {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $tmpRow['finish_number'];
                }
            }
        }


        //不累加--未完工时取完成量最小的员工
        if (!empty($finishUserNumList)) {
            $finishMinNum = '';
            foreach ($finishUserNumList as $finishUserNumRow) {
                if ($finishMinNum === 0) {//如果有员工完成数量为0，
                    break;
                }

                if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                    $finishMinNum = $finishUserNumRow['finish_number'];
                }
            }
            $finishNum = $finishMinNum;
        }

        //统计工序总共使用材料情况 || 调整 按角色区分
        $orderProcessInfo = $order_process_info;//变量保持一致
        $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
        $orderPorcessCourseIds = [];
        $orderMaterialListTmp = [];
        foreach ($orderProcessCourseList as $orderProcessCourseRow) {
            $tmpUid = $orderProcessCourseRow['uid'];
            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type'],'order_process_course_id'=>$orderProcessCourseRow['id']])->get()->toArray();

            foreach ($orderMaterialArr as $orderMaterialRow) {
                if(isset($orderMaterialListTmp[$tmpPrivilegeId])){
                    if (isset($orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']])) {
                        $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                        $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                        $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                        $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']]['retreat_number'] += $orderMaterialRow['retreat_number'];
                    } else {
                        $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']] = $orderMaterialRow;
                    }

                }else{
                    $orderMaterialListTmp[$tmpPrivilegeId] = [];
                    $orderMaterialListTmp[$tmpPrivilegeId][$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

        }


        $orderMaterialList = [];
        foreach ($orderMaterialListTmp as $tmpPrivilegeId => $orderMaterialListTmp) {
            foreach ($orderMaterialListTmp as $orderMaterialRow){
//                $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
                $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);
                if(!$materialRow){
                    $materialRow = ProductEngine::getProductInfoTrash($orderMaterialRow['material_id']);
                    $materialRow['product_name'] = $materialRow['product_name']."[已删除]";
                }
                //追加材料图片地址
                $materialRow['img_url'] = '';
                if($materialRow['img_id']){
                    $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
                }

                //追加材料自定义属性
                $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                $where = ['product_id'=>$materialRow['id']];
                $productFields = $ProductFieldsModel->getData($where);

                $productFields = $productFields->map(function($item){
                    $data['field_name'] = $item->field_name;
                    $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                    $data['field_value'] = $item->$comumnName;
                    return $data;
                });

                $materialRow['custom_fields'] = $productFields;

                $orderMaterialRow['info'] = $materialRow;
                $orderMaterialList[$tmpPrivilegeId][] = $orderMaterialRow;
            }
        }

        foreach ($orderMaterialList as $tmpPrivilegeId => $tmpOrderMaterialList){
            $tmpUserList[$tmpPrivilegeId]['orderMaterialList'] = $tmpOrderMaterialList;
        }

        //角色列表排序
        $where = [];
        $where['ordertype_process_id'] = $order_process_info['ordertype_process_id'];
        $where['action_type'] = 4;

        $ordertypeProcessPrivilegeList = \App\Eloquent\Ygt\OrdertypeProcessPrivilegeSort::where($where)->orderBy('sort','desc')->get();

        $tmpArr = [];//保存排序后角色列表信息
        foreach ($ordertypeProcessPrivilegeList as $ordertypeProcessPrivilegeRow){
            if(isset($tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']])){
                $tmpArr[$ordertypeProcessPrivilegeRow['privilege_id']] = $tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']];
                unset($tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']]);
            }
        }

        foreach ($tmpUserList as $tmpPrivilegeId => $tmpRow){
            $tmpArr[$tmpPrivilegeId] = $tmpRow;
        }

        $list = array_values($tmpArr);


        $isAllowReset = 1;//是否允许重新派单 1-允许 2-不允许
        //如果工单已经开工，不允许再开工
        if ($order_process_info['status'] == 3 || $order_process_info['status'] == 4) {
            $isAllowReset = 2;
        }

        //如果工序管理员不允许重新分派工单
        if ($userId != $order_process_info['uid'] && $userId != $orderinfo['uid']) {
            $isAllowReset = 2;
        }

        //是否显示金额相关的数据 true-隐藏  false-显示
        $isHideMoneyData = OrderEngine::getHideMoneyDataByProcessId($order_process_info['process_type']);


        //获取上一个部门
        $orderInfo = $orderinfo;//变量统一
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $preFinishNum = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $lastOrderProcessId = $orderProcessInfo['id'];

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加

                if ($orderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                    $preFinishNum = 0;

                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {


                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = date('Y年m月d日H时', $preProcessEstimatedTime);
                        }

                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if(!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])){
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $preFinishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $preFinishNum = $finishMinNum;
                    }

                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
        }

        $preProcessInfo = [
            'preProcess' =>	$preProcess,
            'preProcessEstimatedTime' =>	$preProcessEstimatedTime,
            'preProcessEstimatedTimeStr' =>	$preProcessEstimatedTimeStr,
            'lastOrderProcessId' =>	$lastOrderProcessId,
            'finishNum' =>	$preFinishNum,
        ];

        return compact('processInfoStr', 'isAllowReset', 'orderProcessId', 'finishNum', 'allMoney', 'orderinfo', 'list','isHideMoneyData','preProcessInfo');
    }

    //获取未议定价格订单列表
    public function getCustomerOrderNoDealPriceList(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId  = $userInfo['company_id'];

        $customerOrderList = \App\Eloquent\Ygt\CustomerOrder::where(['company_id'=>$companyId,'is_deal_price'=>0])->get()->toArray();
        $tmpOrderList = [];
        foreach ($customerOrderList as $tmpCustomerOrderRow) {
            if (isset($tmpCustomerOrderRow['product_num'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['product_num']);
                $tmpCustomerOrderRow['product_num'] = '';
                foreach ($tmpArr as $tmpValue) {
                    $tmpCustomerOrderRow['product_num'] .= $tmpValue;
                }
            }

            //成品规格数据处理
            if (isset($tmpCustomerOrderRow['finished_specification'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['finished_specification']);
                if (count($tmpArr) == 2) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
                }

                if (count($tmpArr) == 3) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                }

                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($tmpArr as $tmpValue) {
                    if ($tmpValue) {
                        $hasData = true;
                    }
                }

                if (!$hasData) {
                    $tmpCustomerOrderRow['finished_specification'] = '';
                }
            }

            //单位名称显示处理
            if (isset($tmpCustomerOrderRow['field_name_23'])) {
                $baseId = $tmpCustomerOrderRow['field_name_23'];
                $showTitle = Buyers::getNameById($tmpCustomerOrderRow['field_name_23']);
                if (!$showTitle) {
                    $showTitle = $tmpCustomerOrderRow['field_name_23'];
                }
                $tmpCustomerOrderRow['field_name_23'] = $showTitle;
            }

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $orderCreateTime = $tmpCustomerOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');

            $tmpOrderList[] = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($tmpCustomerOrderRow['product_name']) ? $tmpCustomerOrderRow['product_name'] : '',//新加字段品名
                'order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                'secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpCustomerOrderRow['id'],
                'orderStatus' => '',
                'statusColor' => 'FFB401',
            ];
        }

        $orderList = $tmpOrderList;

        $re['pageID'] = 0;
        $re['data']['tableviewSource'] = $orderList;

        return $re;

        return $customerOrderList;
    }

    //获取未议定价格订单详情
    public function getCustomerOrderNoDealPriceDetail(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId  = $userInfo['company_id'];

        $customerOrderId = request('customer_order_id');
        $customerOrderRow =\App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first()->toArray();
        $customerOrderPriceRow = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();


        //订单详情信息
        /****订单创建详情页-基础信息****/
        //订单基础信息字段，目前格式固定
        //用户id&企业id
        $orderEngine = new OrderEngine();
        $orderBaseFieldList = $orderEngine->orderBaseFieldList($companyId);

        //添加默认值
        $allDataList = [];//包含订单基础信息和工序信息
        $curOrderRow = $customerOrderRow;
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                $orderBaseFieldList[$key]['deal_field_name'] = 'base___'.$orderBaseFieldList[$key]['field_name'];
                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {
                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

                        $customerAddressRow = CustomerAddress::where(['id' => $customerAddressId])->first();
                        $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];

                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }

                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);
                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }
            }

            $allDataList[] = [
                'title' => '基础信息',
                'field_list' => $orderBaseFieldList,
            ];

        }

        /****工单创建详情页-工单信息****/
        $processList = [];
        //第一个工序
        $orderTypeObj = new \App\Engine\OrderType();
        $firstProcessId = $orderTypeObj->getFirstOneProcessId($curOrderRow['order_type']);
        $curProcessId = $firstProcessId;

        while ($curProcessId) {
            //通过工序id，获取对应的字段
            $processFieldList = Process::getFieldListByProcessId($curProcessId);
            //获取工序信息
            $processTitle = Process::getOneValueById($curProcessId, 'title');

            $curOrderProcessRow = [];
            if ($curOrderRow['id']) {//如果传入复制工单id
                $curOrderProcessRow = \App\Eloquent\Ygt\CustomerOrderProcess::where(['order_id' => $curOrderRow['id'], 'process_type' => $curProcessId])->first();
                if (!empty($curOrderProcessRow)) {
                    $curOrderProcessRow = $curOrderProcessRow->toArray();
                }
            }

            //添加默认值
            foreach ($processFieldList as $key => $row) {
                $processFieldList[$key]['deal_field_name'] = $curProcessId.'___'.$processFieldList[$key]['field_name'];
                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);

                        $materialList = [];
                        foreach ($materialIdList as $materialId) {
                            $materiaRow = ProductEngine::getProductInfo($materialId);
                            if ($materiaRow) {//过滤异常情况
                                $materiaRow->toArray();
                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materiaRow['product_no'],
                                    'product_name' => $materiaRow['product_name'],
                                ];
                            }
                        }
                        $processFieldList[$key]['default_product_list'] = $materialList;
                    } elseif ($row['field_type'] == 17) {//版 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $plateRow = PlateEngine::getPlateInfo($selectId);

                        if ($plateRow) {
                            $showTitle = $plateRow['plate_name'];
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }

                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }
                }
            }

            $curProcess = [
//                'process_id' => $curProcessId,
                'title' => $processTitle,
                'field_list' => $processFieldList,
            ];
            $allDataList[] = $curProcess;
            //下一个工序
            $curProcessId = $orderTypeObj->getNextOneProcessId($curOrderRow['order_type'], $curProcessId);//获取下一个工序
        }


        return [
            'customer_order_price_tips' => '塑编袋单价',
            'data_list' => $allDataList
        ];




    }

    //提交价格（意见）
    public function customerOrderPriceDeal(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId  = $userInfo['company_id'];

        $customerOrderId = request('customer_order_id');
        $price = request('price');//提交的订单价格
        $dealType = request('deal_type');//是否同意对方的价格 agree-同意  reject-拒绝

        $customerOrderRow =\App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first()->toArray();


        //销售员角色提交价格
        if($customerOrderRow['customer_name'] != $userId){
            if(!$dealType){
                //第一次提交价格
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id'=>$customerOrderId]);
                if($customerOrderPriceObj->count()){
                    return [
                        'code' => '1',
                        'message' => '操作异常'
                    ];
                }

                $eidtRow = [
                    'customer_order_id' => $customerOrderId,
                    'sale_price' => $price,
                    'status' => 1,
                    'sale_uid' => $userId,
                    'customer_uid' => $customerOrderRow['customer_name'],
                ];
                $customerOrderPriceObj->fill($eidtRow);
                $customerOrderPriceObj->save();

                //发送消息
                $data           = [
                    'company_id'=> $customerOrderRow['company_id'],
                    'privilege_id'=> '',
                    'form_user_id'=> $userId,
                    'to_user_id'=> $customerOrderRow['customer_name'],
                    'foreign_key'=> $customerOrderId,
                    'type'=>19,
                    'type_id'=>$customerOrderId,
                    'title'=>'订单价格',
                    'content'=>'销售员提交了新价格'
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }else{
                //对客户新提的价格进行处理
                if($dealType == 'agree'){
                    //双方价格确定
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
                    if($customerOrderPriceObj){
                        if($customerOrderPriceObj->status == 2){
                            //价格确定
                            $eidtRow = [
                                'customer_order_id' => $customerOrderId,
                                'customer_price' => $customerOrderPriceObj->sale_price,
                                'deal_price' => $customerOrderPriceObj->sale_price,
                                'status' => 3,
                            ];
                            $customerOrderPriceObj->fill($eidtRow);
                            $customerOrderPriceObj->save();

                            //发送消息
                            $data           = [
                                'company_id'=> $customerOrderRow['company_id'],
                                'privilege_id'=> '',
                                'form_user_id'=> $userId,
                                'to_user_id'=> $customerOrderRow['customer_name'],
                                'foreign_key'=> $customerOrderId,
                                'type'=>19,
                                'type_id'=>$customerOrderId,
                                'title'=>'订单价格',
                                'content'=>'销售员同意了价格'
                            ];
                            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);

                        }else{
                            return [
                                'code' => '3',
                                'message' => '操作异常'
                            ];
                        }
                    }else{
                        return [
                            'code' => '2',
                            'message' => '操作异常'
                        ];
                    }

                }elseif($dealType == 'reject'){
                    //价格确定
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
                    $eidtRow = [
                        'sale_price' => $price,
                        'status' => 1,
                    ];
                    $customerOrderPriceObj->fill($eidtRow);
                    $customerOrderPriceObj->save();

                    //发送消息
                    $data           = [
                        'company_id'=> $customerOrderRow['company_id'],
                        'privilege_id'=> '',
                        'form_user_id'=> $userId,
                        'to_user_id'=> $customerOrderRow['customer_name'],
                        'foreign_key'=> $customerOrderId,
                        'type'=>19,
                        'type_id'=>$customerOrderId,
                        'title'=>'订单价格',
                        'content'=>'销售员不同意提交的价格，并提交了新价格'
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);


                }else{
                    return [
                        'code' => '1',
                        'message' => '操作异常'
                    ];
                }

            }

            return '操作成功';
        }

        //客商提交价格
        if($customerOrderRow['customer_name'] == $userId){
            //对销售员新提的价格进行处理
            if($dealType == 'agree'){
                //双方价格确定
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
                if($customerOrderPriceObj){
                    if($customerOrderPriceObj->status == 1){
                        //价格确定
                        $eidtRow = [
                            'customer_order_id' => $customerOrderId,
                            'sale_price' => $customerOrderPriceObj->customer_price,
                            'deal_price' => $customerOrderPriceObj->customer_price,
                            'status' => 3,
                        ];
                        $customerOrderPriceObj->fill($eidtRow);
                        $customerOrderPriceObj->save();

                        //发送消息
                        $data           = [
                            'company_id'=> $customerOrderRow['company_id'],
                            'privilege_id'=> '',
                            'form_user_id'=> $userId,
                            'to_user_id'=> $customerOrderPriceObj->sale_uid,
                            'foreign_key'=> $customerOrderId,
                            'type'=>19,
                            'type_id'=>$customerOrderId,
                            'title'=>'订单价格',
                            'content'=>'客商同意了价格'
                        ];
                        \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);

                    }else{
                        return [
                            'code' => '3',
                            'message' => '操作异常'
                        ];
                    }
                }else{
                    return [
                        'code' => '2',
                        'message' => '操作异常'
                    ];
                }

            }elseif($dealType == 'reject'){
                //价格确定
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
                $eidtRow = [
                    'customer_price' => $price,
                    'status' => 2,
                ];
                $customerOrderPriceObj->fill($eidtRow);
                $customerOrderPriceObj->save();

                //发送消息
                $data           = [
                    'company_id'=> $customerOrderRow['company_id'],
                    'privilege_id'=> '',
                    'form_user_id'=> $userId,
                    'to_user_id'=> $customerOrderPriceObj->sale_uid,
                    'foreign_key'=> $customerOrderId,
                    'type'=>19,
                    'type_id'=>$customerOrderId,
                    'title'=>'订单价格',
                    'content'=>'客商不同意提交的价格，并提交了新价格'
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);

            }else{
                return [
                    'code' => '1',
                    'message' => '操作异常'
                ];
            }


            return '操作成功';
        }


        return [
            'code' => '4',
            'message' => '操作异常'
        ];

    }


    //设置工单员工计件工资
    public function setOrderPieceWage(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId  = $userInfo['company_id'];

        $orderProcessCourseId = request('order_process_course_id');//员工工单ID
        $pieceWage = request('piece_wage');//计件工资


        $orderProcessCourseRow = \App\Eloquent\Ygt\OrderProcessCourse::where(['id'=> $orderProcessCourseId])->first()->toArray();
        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$orderProcessCourseRow['order_process_id']])->first()->toArray();
        $orderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderProcessRow['order_id']])->first()->toArray();


        $orderWageObj = OrderWage::firstOrNew(['order_process_course_id'=>$orderProcessCourseId]);
        $editRow = [
            'order_id'  => $orderRow['id'],
            'order_process_id'  => $orderProcessRow['id'],
            'order_process_course_id'  => $orderProcessCourseRow['id'],
            'employee_id'  => $orderProcessCourseRow['uid'],
            'manager_id'  => $userId,
            'piece_wage'  => $pieceWage,
        ];
        $orderWageObj->fill($editRow);
        $orderWageObj->save();

        return '操作成功';
    }


    //批量设置工单员工计件工资
    public function setOrderPieceWageAll(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId  = $userInfo['company_id'];

        $orderProcessId = request('order_process_id');//员工工单ID
        $privilegeId = request('privilege_id');//工序工单对应的
        $pieceWage = request('piece_wage');//计件工资

        //获取角色下有哪些用户id
        $userIds = \App\Eloquent\Ygt\DepartmentUser::where(['privilege_id'=>$privilegeId,'company_id'=>$companyId])->get()->pluck('user_id');

        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$orderProcessId])->first()->toArray();
        $orderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderProcessRow['order_id']])->first()->toArray();

        $orderWageObj = OrderWage::firstOrNew(['order_process_id'=>$orderProcessId,'privilege_id'=>$privilegeId]);
        $editRow = [
            'order_id'  => $orderRow['id'],
            'order_process_id'  => $orderProcessRow['id'],
            'privilege_id'  => $privilegeId,
            'manager_id'  => $userId,
            'piece_wage'  => $pieceWage,
        ];
        $orderWageObj->fill($editRow);
        $orderWageObj->save();

        return '操作成功';
    }

    //完整订单打印
    public function getCustomerOrderDetailPrint(){
        //数据收集
        $customerOrderId = request('customer_order_id');

        

    }



    //获取工单列表筛选状态列表
    public function getOrderListFilterStatus()
    {
        $orderListFilterStatus = [
            [
                'title' => '全部',
                'value' => '',
            ],
            [
                'title' => '待开工',
                'value' => '1',
            ],
            [
                'title' => '进行中',
                'value' => '2',
            ],
            [
                'title' => '已完成',
                'value' => '3',
            ]
        ];

        return $orderListFilterStatus;
    }


    //工单基础页面字段
    public function orderBaseFieldList()
    {
        return [
            [
                'field_name' => 'customer_name',
                'title' => '客户',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'product_name',
                'title' => '品名',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'contract_number',
                'title' => '合同编号',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
//            [
//                'field_name' => 'enterprise_icon',
//                'title' => '企业图标',
//                'field_type' => 9,
//                'placeholder' => '请上传',
//                'new_page_title' => '上传企业图标',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
            [
                'field_name' => 'finished_date',
                'title' => '交货日期',
                'field_type' => 7,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'add_distribution_address',
                'title' => '添加配送地址',
                'field_type' => 8,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'product_num',
                'title' => '下单数量',
                'field_type' => 5,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [
                    [
                        'id' => 1,
                        'title' => '米'
                    ],
                    [
                        'id' => 2,
                        'title' => '条'
                    ]
                ],
                'data' => [],
            ],
//            [
//                'field_name' => 'chip_specification_length',
//                'title' => '片料规格-长',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'chip_specification_width',
//                'title' => '片料规格-宽',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'grammage',
//                'title' => '克数',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'weaving_type',
//                'title' => '织布类型',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_numbering',
//                'title' => '印版编号',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_position',
//                'title' => '印版位置',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'public_plate',
//                'title' => '公用印版',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_modification',
//                'title' => '印版修改',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'finished_weight',
//                'title' => '成品重量',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
            [
                'field_name' => 'is_priority',
                'title' => '优先处理',
                'field_type' => 6,
                'placeholder' => '',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'production_case_diagram',
                'title' => '生产实例图',
                'field_type' => 9,
                'placeholder' => '请上传',
                'new_page_title' => '上传企业图标',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ]
        ];
    }

    public function getUnitIdByTitle($unitTitle, $unitList)
    {
        foreach ($unitList as $unitRow) {
            if ($unitRow['title'] == $unitTitle) {
                return $unitRow['id'];
            }
        }
        return false;
    }

    public function getSidByTitle($dataTitle, $dataList)
    {
        foreach ($dataList as $dataRow) {
            if ($dataRow['title'] == $dataTitle) {
                return $dataRow['id'];
            }
        }
        return false;
    }

    public function getProcessCourseInfoWithList()
    {
        $orderProcessId = request('order_process_id');

        $order_process_info = OrderProcess::where('id', $orderProcessId)->first();

        $processTitle = Process::getOneValueById($order_process_info['process_type'], 'title');

        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];
        $processStatusStr = $statusArray[$order_process_info['status']];
        $processInfoStr = $processStatusStr . '[' . $processTitle . ']';

        $orderinfo = $this->info($order_process_info->order_id);

        ////替换产品名称为工序类型名称
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderinfo['order_type'], 'title');
        $orderinfo['product_name'] = $orderTypeTitle;

        $list = OrderProcessCourse::getAllWithUser($orderProcessId, $order_process_info['company_id']);

        //增加限制
        $userId = Func::getHeaderValueByName('userid');
        foreach ($list as &$row) {
            $row['is_allow_write'] = 0;
            if ($userId == $order_process_info['uid']) {//允许
                $row['is_allow_write'] = 1;
            }
        }


        $courseStatusArray = [
            '1' => '待开工',
            '2' => '待领取材料',
            '3' => '生产中',
            '4' => '已完成',
        ];
        $list->transform(function ($item) use ($courseStatusArray) {
            $item->statusStr = $courseStatusArray[$item->status];
            $item->creat_time = $item->created_at->formatLocalized('%Y-%m-%d');
            if (!$item->waste_number) {
                $item->waste_number = 0;
            }
            return $item;
        });


        //统计工序完成数量
        $processIsSum = Process::getOneValueById($order_process_info['process_type'], 'is_sum');

        $tmpUserList = [];
        $finishUserNumList = [];
        //员工分组，按角色分类
        $allMoney = 0;//总计件工资
        $finishNum = 0;//总完成数量
        foreach ($list as $tmpRow) {
            $tmpUid = $tmpRow->uid;

            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');

            $tmpRow->price = $tmpUserInfo['price'];
            $tmpRow->money = $tmpUserInfo['price'] * $tmpRow['finish_number'];

            if (isset($tmpUserList[$tmpPrivilegeId])) {
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] += $tmpRow->finish_number;//同角色总数量
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] += $tmpRow->finish_number * $tmpRow->price;//同角色总计件工资
                $tmpUserList[$tmpPrivilegeId]['sumUserNum']++;//同角色总人数

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            } else {
                $tmpUserList[$tmpPrivilegeId]['privilegeId'] = $tmpPrivilegeId;
                $tmpUserList[$tmpPrivilegeId]['privilegeTitle'] = $tmpPrivilegeTitle;
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] = $tmpRow->finish_number;
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] = $tmpRow->finish_number * $tmpRow->price;
                $tmpUserList[$tmpPrivilegeId]['sumUserNum'] = 1;

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            }


            //设定的角色不进行统计数量到工序数量中
            //过滤异常数据
            if(!DepartmentUser::getCurrentInfo($tmpRow->uid)){
                continue;
            }
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpRow->uid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                continue;
            }


            $finishNum += $tmpRow->finish_number;

            if (!$processIsSum) {//不累加
                if (isset($finishUserNumList[$tmpPrivilegeId])) {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $tmpRow['finish_number'];
                } else {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $tmpRow['finish_number'];
                }
            }
        }


        //不累加--未完工时取完成量最小的员工
        if (!empty($finishUserNumList)) {
            $finishMinNum = '';
            foreach ($finishUserNumList as $finishUserNumRow) {
                if ($finishMinNum === 0) {//如果有员工完成数量为0，
                    break;
                }

                if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                    $finishMinNum = $finishUserNumRow['finish_number'];
                }
            }
            $finishNum = $finishMinNum;
        }


        $list = array_values($tmpUserList);


        $isAllowReset = 1;//是否允许重新派单 1-允许 2-不允许
        //如果工单已经开工，不允许再开工
        if ($order_process_info['status'] == 3 || $order_process_info['status'] == 4) {
            $isAllowReset = 2;
        }

        //如果工序管理员不允许重新分派工单
        if ($userId != $order_process_info['uid'] && $userId != $orderinfo['uid']) {
            $isAllowReset = 2;
        }

        //是否显示金额相关的数据 true-隐藏  false-显示
        $isHideMoneyData = OrderEngine::getHideMoneyDataByProcessId($order_process_info['process_type']);

        return compact('processInfoStr', 'isAllowReset', 'orderProcessId', 'finishNum', 'allMoney', 'orderinfo', 'list','isHideMoneyData');
    }

    public function info($id)
    {
        $info = Order::where('id', $id)->select([
            'id',
            'order_type',
            'order_title',
            'contract_number',
            'customer_name',
            'product_name',
            'product_num',
            'unit',
            'grammage',
            'chip_specification_length',
            'chip_specification_width',
            'finished_specification',
            'finished_weight',
            'finished_date',
            'created_at',
            'updated_at',
            'weaving_type',
            'plate_numbering',
            'plate_position',
            'plate_modification',
            'public_plate',
            'is_priority',
            'enterprise_icon',
            'production_case_diagram',
            'status',
            'uid',
            'company_id',
            'order_pre_id',
        ])->first();
        $info->create_time = $info->created_at->formatLocalized('%Y-%m-%d %H:%M:%S');
        $info->updated_time = $info->updated_at->formatLocalized('%Y-%m-%d %H:%M:%S');

        $orderTypeInfo = \App\Eloquent\Ygt\OrderType::where('id', $info->order_type)->first();

        //处理图片数据
        $imgIdList = explode(',', $info['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        $info->order_type_imgurl = $exampleImg;
        return $info;
    }


    //获取工单报表信息
    public function getOrderReport()
    {
        $orderReportId = request('order_report_id');

        //获取工单报表关系
        $orderReportRow = OrderReport::where(['id' => $orderReportId])->first();
        $orderId = $orderReportRow['order_id'];
        $orderReportTypeId = $orderReportRow['order_report_type_id'];
        $companyId = $orderReportRow['company_id'];

        $orderRow = Order::where(['id' => $orderId])->first();
        $orderReportTypeRow = OrderReportType::where(['id' => $orderReportTypeId])->first();

        $orerReportContentStr = $orderReportTypeRow['content'];
        $orerReportContentList = explode(',', $orerReportContentStr);

        $reportTitle = $orderReportTypeRow['title'];
        $dataDetail = [];

        if (in_array(1, $orerReportContentList)) {
            $dataDetail[] = [
                'type' => 1,
                'title' => '工单号',
                'value' => $orderRow['order_title']
            ];
        }

        if (in_array(2, $orerReportContentList)) {
            $dataDetail[] = [
                'type' => 1,
                'title' => '客户名称',
                'value' => $orderRow['customer_name']
            ];
        }


        $orerProcessCourseAll = $orderMaterialCourseAll = [];
        if (in_array(3, $orerReportContentList) || in_array(4, $orerReportContentList)) {
            //获取工单工序信息
            $orderProcessList = OrderProcess::where(['order_id' => $orderId, 'company_id' => $companyId])->get();
            foreach ($orderProcessList as $orderProcessRow) {
                $orderProcessId = $orderProcessRow['id'];
                //获取工序工单对应的员工工单
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessId, 'company_id' => $companyId])->get();

                //获取对应的员工材料数据
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                    $orerProcessCourseAll[] = $orderProcessCourseRow;

                    if (in_array(4, $orerReportContentList)) {
                        $orderProcessCourseId = $orderProcessCourseRow['id'];
                        $orerProcessCourseMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'company_id' => $companyId])->get();
                        foreach ($orerProcessCourseMaterialList as $orerProcessCourseMaterialRow) {
                            $orderMaterialCourseAll[] = $orerProcessCourseMaterialRow;
                        }
                    }

                }
            }
        }

        //员工收益
        if (in_array(3, $orerReportContentList)) {
            $orerProcessCourseAllDeal = [];
            //统计完成数量
            foreach ($orerProcessCourseAll as $orderProcessCourseRow) {
                $uid = $orderProcessCourseRow['uid'];
                if (isset($orerProcessCourseAllDeal[$uid])) {
                    $orerProcessCourseAllDeal[$uid]['finish_number'] += $orderProcessCourseRow['finish_number'];
                } else {
                    $orerProcessCourseAllDeal[$uid]['finish_number'] = $orderProcessCourseRow['finish_number'];
                    $orerProcessCourseAllDeal[$uid]['uid'] = $uid;
                }
            }
            //获取计件工资数
            $dataList = [];
            foreach ($orerProcessCourseAllDeal as $uid => $orerProcessCourseRow) {
                //获取单件工资
                $userInfo = DepartmentUser::getCurrentInfo($uid)->toArray();

                $dataList[] = [
                    'title' => $userInfo['truename'],
                    'value' => '计件' . $orerProcessCourseRow['finish_number'] . '，' . $userInfo['price'] * $orerProcessCourseRow['finish_number'] . '元'
                ];
            }

            $dataDetail[] = [
                'type' => 2,
                'title' => '员工收益',
                'data' => $dataList
            ];
        }

        //材料损耗
        if (in_array(4, $orerReportContentList)) {
            $orderMaterialCourseAllDeal = [];
            foreach ($orderMaterialCourseAll as $orderMaterialCourseRow) {
                $materialId = $orderMaterialCourseRow['material_id'];
                if (isset($orderMaterialCourseAllDeal[$materialId])) {
                    $orderMaterialCourseAllDeal[$materialId]['receive_number'] += $orderMaterialCourseRow['receive_number'];
                    $orderMaterialCourseAllDeal[$materialId]['scrap_number'] += $orderMaterialCourseRow['scrap_number'];
                    $orderMaterialCourseAllDeal[$materialId]['residual_number'] += $orderMaterialCourseRow['residual_number'];
                } else {
                    $orderMaterialCourseAllDeal[$materialId]['receive_number'] = $orderMaterialCourseRow['receive_number'];
                    $orderMaterialCourseAllDeal[$materialId]['scrap_number'] = $orderMaterialCourseRow['scrap_number'];
                    $orderMaterialCourseAllDeal[$materialId]['residual_number'] = $orderMaterialCourseRow['residual_number'];
                    $orderMaterialCourseAllDeal[$materialId]['material_id'] = $materialId;
                }
            }

            //获取计件工资数
            $dataList = [];
            foreach ($orderMaterialCourseAllDeal as $materialId => $orderMaterialCourseRow) {
                //获取材料信息
                $materiaRow = ProductEngine::getProductInfo($materialId)->toArray();
                //废品率
                $wasteRate = (round(($orderMaterialCourseRow['scrap_number'] / ($orderMaterialCourseRow['receive_number'] - $orderMaterialCourseRow['residual_number'])), 4) * 100) . '%';
                //单位
                $unit = $materiaRow['unit'];
                if (!$unit) {
                    $unit = '无单位';
                }

                $dataList[] = [
                    'title' => $materiaRow['product_name'],
                    'value' => "废品{$orderMaterialCourseRow['scrap_number']}（{$unit}），废品率{$wasteRate}"
                ];
            }

            $dataDetail[] = [
                'type' => 2,
                'title' => '材料损耗',
                'data' => $dataList
            ];
        }

        $data = [
            'report_title' => $reportTitle,
            'dataDetail' => $dataDetail
        ];
        return $data;
    }

    //转变单位名称字段 原因 该字段存值 有三种
    //1单位的id 2单位的名称 3空
    public function changeFieldName23($value = '')
    {
        $result = $value;
        if ($value) {
            $result = Buyers::getNameById($value);
            if (!$result) {
                $result = $value;
            }
        }
        return $result;
    }


    /**
     * Description:测试模块
     * User: zhuyujun
     */
    public function test()
    {



        $companyId=5;
        $purchasingAgentPrivilegeList         = \App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, 10 );
        dd($purchasingAgentPrivilegeList);

        $a=1;$b=1;
        $re = isset($a,$b,$c);
        var_dump($re);die();



        die();
        \DB::connection()->enableQueryLog(); // 开启查询日志
        $obj =  \App\Eloquent\Ygt\CustomerOrder::where(['id'=>1])->where(['id'=>2])->first();
//        $arr = [
//            'order_title' => $obj->order_title.'112233'
//        ];
//        $obj->fill($arr);
//        $obj->save();
        $queries = \DB::getQueryLog(); // 获取查询日志
        dd($queries); die();// 即可查看执行的sql，传入的参数等等
        die();


        $arr = [
            [
                'material_id' => 1,
                'num' => 2,
                'price' => 3,
            ]
        ];

        echo \GuzzleHttp\json_encode($arr);die();




        OrderEngine::importOrderListRelation();
        die('import success!');


        $result = OrderType::getAllStepsWithDistribution(39);

        //获取工序可分派给工序管理员的列表
        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        dd($result->toArray());

        $tmp = new Request();
        $re = $this->getManagerOrderDetailListNew($tmp);
        dd($re);

        $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess(39, 8, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
        dd($privilegeIds->count());
        //获取方法名
//        $orderPreId = 45;
//        $orderModels = new OrderModels();
//        $orderPreRow = $orderModels->getOrderPreInfo($orderPreId);
//        $orderModels->insertOrder($orderPreRow);
    }
}


if (!function_exists('request')) {
    /**
     * Get an instance of the current request or an input item from the request.
     *
     * @param  array|string $key
     * @param  mixed $default
     * @return \Illuminate\Http\Request|string|array
     */
    function request($key = null, $default = null)
    {
        if (is_null($key)) {
            return app('request');
        }

        if (is_array($key)) {
            return app('request')->only($key);
        }

        return data_get(app('request')->all(), $key, $default);
    }
}